4
def spam():
    print(eggs)
    eggs = 13

eggs = 12
spam()

This gives the error:

UnboundLocalError: local variable 'eggs' referenced before assignment

But this does not:

def spam():
    print(eggs)


eggs = 12
spam()

Why?

Nordle
  • 2,915
  • 3
  • 16
  • 34
Yash Gupta
  • 41
  • 3
  • Because the first version contains an assignment to `eggs`, it is assumed to be a local variable. The second version contains no assignment to `eggs`, so it is assumed to be a global variable. – khelwood May 24 '19 at 10:54
  • The reasoning is, you don't want `eggs` suddenly changing from global to local in the middle of your first function; and you don't want it to silently modify a global variable unless you have declared your intention to do so. – alexis May 24 '19 at 11:02
  • Possible duplicate of [Python variable scope error](https://stackoverflow.com/questions/370357/python-variable-scope-error) – sanyassh May 24 '19 at 11:20

1 Answers1

2

In the first example, when you do eggs = 13, the function tries to find the definition within it's scope, assuming it as a local variable,and since no such variable is defined within the function, local variable 'eggs' referenced before assignment. exception is thrown.

In the second example, since no such assignment is present, eggs is taken from the global scope, which is eggs=12, hence no such exception is thrown here

To resolve this issue, you need to assign a local variable eggs within the function. Here only the local variable eggs is referenced to and changed, the global variable eggs is the same.

In [40]: def spam(): 
    ...:     eggs = 12 
    ...:     print(eggs) 
    ...:     eggs = 13 
    ...:     print(eggs) 
    ...:  
    ...: eggs = 12 
    ...: spam() 
    ...: print(eggs)                                                                                                                                                                
12
13
12
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40
  • Great! Glad to help :) Please consider marking the answer as accepted if it helped you by clicking the tick next to the answer @YashGupta Also consider reading up on https://stackoverflow.com/help/someone-answers and https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Devesh Kumar Singh May 24 '19 at 10:59