Scope in python basically works like this.
Any time I have a variable, it has a scope, which is you can think of as the range where it can be accessed. Any code in that range can access and change my variable.
A variable like this
myint = 123
Can be access basically anywhere in my code. Except inside of a function, since functions have their own scope. I’ll get to that later.
So this code will print myint:
myint = 123
if myint == 123:
print(f"Your Int: {myint}")
But say for example, I declare myint
inside of an if statement, like this:
if 1 == 1:
myint = 123
Then the variable myint
’s scope is only inside of that if statement. If I try and access it outside of the if statement, like this:
if 1 == 1:
myint = 123
print(myint)
I’ll get an error that myint
is undefined, because it’s scope is only inside that if statement.
To fix this, I need to declare it outside of the if statement, and then I can access it.
myint = 0
if 1 == 1:
myint = 123
print(myint)
Now I mentioned earlier that Functions have their own scope. A variable declared outside of a function won’t be able to be accessed inside of a function unless you declare it as global.
This won’t work:
myint = 123
def print_myint():
print(myint)
If I run that code I’ll get an error saying I might be trying to access a local variable.
to make myint
available inside the scope of my function, I can declare it as a global variable
myint = 123
def print_myint():
global myint
print(myint)
That code above will work
Hopefully this makes it clear, if it doesn’t, just ask and I’ll try and explain it better.