Why does following code work well in Python?
def show():
print(a)
a = 1
show()
I think if we use show function before assignment (a = 1),
undefined error for a should be output.
However, beyond my expectation the code above works well....
Why does following code work well in Python?
def show():
print(a)
a = 1
show()
I think if we use show function before assignment (a = 1),
undefined error for a should be output.
However, beyond my expectation the code above works well....
The content of the function "show" runs only after "show" function is being called. You're calling "show" function after you're assigning variable a value (a=1), and that's why an error is not being thrown.
The code run as follows:
What a function definition like the one in your code actually means:
def show():
print(a)
It defines a function that, when executed, will print the value named a. And because that name is not defined in the function itself, it will refer to a global variable (or cause an error if the name isn't defined when the function is executed).
Your code then goes on, after the function definition, to define a:
a = 1
And finally, the function you defined is actually executed, this is the first time the code in the function will actually run, and because you defined a beforehand, it will correctly print "1".
show()