1
def callme():
    print(x)
    x=20
x=10
callme()

x = 10 is assigned globally(line-4), callme() calls def callme(): executes first, then comes print(x), So it has to print 10, because python doesn't knows that there exists a variable x=20 in the 3rd line. But these lines prints error.

def callme():
    print(x)
x=10
callme()

But in this case, it prints 10. because x is defined as global variable.

Can anyone clarify this?

Axe319
  • 4,255
  • 3
  • 15
  • 31
  • 3
    I recently explained it on [this question](https://stackoverflow.com/questions/69601011/how-scope-is-determined-in-python). – Troll Oct 21 '21 at 10:55
  • 1
    If there is an assignment of a variable in a function, in this case `x`. Then any references to that variable prior to the assignment will result in an `UnboundLocalError`. – Axe319 Oct 21 '21 at 10:55
  • 1
    "because python doesn't knows that there exists a variable x=20 in the 3rd line" Python can (and does) look at the entire source code before execution. – MisterMiyagi Oct 21 '21 at 10:56
  • 2
    Actually Python do know that there is a local variable in your function. Python is reading your whole file before executing and therefore it saves some informations. That's why you are getting an error, because Python think you want to work locally and not globally. Take a look at the comment from @MartesBerkeley for more informations. – Maik Hasler Oct 21 '21 at 11:00

0 Answers0