-1

I'm still in the process of learning python and there is a problem that I am not able to understand.

def demo():
  print(a)
  a += 5

a = 100
print(a)
demo()
print(a)

If i run this program it gives a traceback error which is obvious. But the problem comes when I run the below code.

def demo():
  print(a)

a = 100
print(a)
demo()
print(a)

If I remove the a += 5 line then the program runs just fine and produce the output -

100
100
100

My question is that it should still give traceback error because I still have not yet defined what a is in the function body and neither did I give a as argument. But it doesn't give the error. Can anyone please explain it to me why it is ?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
CodeSpec
  • 31
  • 6
  • 1
    In the second one a is a global variable, in the first one since you try to change it in the function it is a local one. – luk2302 Mar 19 '23 at 12:09
  • Does this answer your question? [UnboundLocalError trying to use a variable (supposed to be global) that is (re)assigned (even after first use)](https://stackoverflow.com/questions/370357/unboundlocalerror-trying-to-use-a-variable-supposed-to-be-global-that-is-rea) – Tomerikoo Mar 19 '23 at 12:21
  • And [Why isn't the 'global' keyword needed to access a global variable?](https://stackoverflow.com/q/4693120/6045800) – Tomerikoo Mar 19 '23 at 12:22

1 Answers1

1

In this case, a is in the global/module scope. It can be read from functions as long as it's only read, but if a function writes to it then it's assumed to be local so it will cause the print to error. If you do want to assign to the global a from demo you have to mark it as such with a global statement.

def demo():
  global a
  print(a)
  a += 5

a = 100
print(a)
demo()
print(a)
100
100
105
Sweet Sheep
  • 326
  • 1
  • 6