Now, unlike some other programming languages,
if you've come from say C++ or Java,
there is no such thing as block scope in Python.
What this means is that if you were to create an if statement,
say if 3 > 2,
and if you were to create a new variable inside an if block or a while loop or a
for loop, basically any sort of block of code that's indented,
this does not count as offence.
It still has the same scope as its enclosing function,
or if there is no enclosing function then it has global scope.
So let me show you a full example. Let's say we had a list of enemies,
so the enemies could be skeletons, zombies, or aliens. So now,
if I was to define a game level, right?
Like the level that the user is currently playing at,
let's say they're on level 3.
And I create an if statement and I check if the game_level is less than level
5, well, in that case, I want to create a new enemy,
but I don't want the enemy to be too difficult to beat.
So I'm going to pick from the list of enemies and I'm going to pick the first
one. Notice how,
even though this new enemy is a variable that's created within this
if block, if I go outside the if block
so I'm not indented at all anymore, and I try to print this new enemy,
this is perfectly valid code. And if I run the code,
you'll see skeleton being printed.
But notice how as soon as I embed this within a function,
so let's define a new function.
And now this line error is out because within the function there is local scope.
So now this new enemy is available anywhere within this function,
because blocks like if, while, for, all of these blocks of code with colons and
indentation, they don't count as creating a local scope.
So in order to print this new enemy,
I actually have to be within the boundary of this function,
which means my code has to be here.
The most important thing to remember from this is if you create a variable
within a function, then it's only available within that function.
But if you create a variable within an if block or a while loop or a for loop or
anything that has the indentation and the colon,
then that does not count as creating a separate local scope.