0

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?

Damanpreet kaur
  • 123
  • 3
  • 16
  • You assign to `line` in the first version, so it is a local variable. – kindall Jun 14 '20 at 04:50
  • https://docs.python.org/3/faq/programming.html#what-are-the-rules-for-local-and-global-variables-in-python "If a variable is assigned a value **anywhere** within the function’s body, it’s assumed to be a local unless explicitly declared as global." The function is defined before it is run, so the parser has already identified local and global variables (as well as arguments). – hpaulj Jun 14 '20 at 06:43
  • @hpaulj That answers my question. Thank you very much! – Damanpreet kaur Jun 15 '20 at 04:31

1 Answers1

0

well, first python reads

line = "hello"

then does the function

f()

(because the function CALL is after the line = "hello")

MatthewProSkils
  • 364
  • 2
  • 13