Yash Gupta
Yash Gupta

Reputation: 41

Python Local and Global Variables

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?

Upvotes: 4

Views: 97

Answers (1)

Devesh Kumar Singh
Devesh Kumar Singh

Reputation: 20490

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

Upvotes: 2

Related Questions