Variable scope (local variables)
The parameters of the functions and any variables defined inside the function block are local variables.
This means that the parameters and variables are not accessible from outside the function.
def f(x):
return x**2
y = f(4)
print(x) # Error! What is the message?
You can define another x
outside the function definition, but this will be a completely different x
than the one inside the function definition.
def f(x):
print("Inside f(x)")
print(x) # What does this print?
return x**2
x = 5
y = f(4)
print("Outside f(x)")
print(x) # What does this print?
This is the point where I would like to ask you to read Sections 3.7, 3.8 and 3.9 of Think Python 2nd Edition.
I (Josiah) think that the author did a fabulous job explaining how Python stack traceback works. There is no point in me trying to reproduce it. No, I am not being lazy, honest! 😆
So, please, go read Think Python 2nd Edition Sections 3.7, 3.8, and 3.9. Then come back here once you are done. I will be waiting! 😴