Why can we use global variable before assignment in Python?

Viewed 66

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....

2 Answers

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:

  1. Defining the function "show" but not running its content
  2. Setting value of variable a to 1
  3. Calling the function "show"
  4. Printing the value of variable a, which is 1

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()
Related