I am not sure if this has been answered before. I would really appreciate it if someone can explain this. As python is an interpreted language, how does python recognize that the variable line in the below example is declared after the print statement?
def f():
print(line)
line = "Hello World!"
print(line)
line = "Hello!"
f()
Running the above code throws an error-
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'line' referenced before assignment
While the below works fine -
def f():
print(line)
line = "Hello!"
f()
Output: Hello World!
For the second example, I understand that since the line variable is declared before the function call, python recognizes the global value of the line variable and prints it. Why does python not recognize the global value of the line variable in the first example?