Dr C
Dr C

Reputation: 150

python if statement causing errors

someStuff = False
def spawn():
    print(someStuff)
    if( 3==4):
       someStuff = True  
while (someStuff==False):
    spawn()

Here's the code, print(someStuff) does not work, it says "UnboundLocalError: local variable 'someStuff' referenced before assignment". However, if the if statement is taken out, then it works.

Upvotes: 0

Views: 55

Answers (3)

Steven Rumbalski
Steven Rumbalski

Reputation: 45542

The assignment someStuff = True in your function tells Python that you will be creating a local variable someStuff. Python then sees the reference to someStuff in print(someStuff) before the assignment and complains. You need to resolve this ambiguity by declaring someStuff to be global. Make the first line of you function be global someStuff. Note that doing so means that the later assignment will affect the global variable.

Upvotes: 1

khelwood
khelwood

Reputation: 59113

If you have this:

def spawn():
     print(someStuff)

python will assume that someStuff must be a global variable. However, if you have an assignment in your function:

def spawn():
     print(someStuff)
     if 3==4:
         someStuff = True

then python assumes it is a local variable that needs to be assigned before it is used.

You can let python know it is global by putting global someStuff in your function:

def spawn():
     global someStuff
     print(someStuff)
     if 3==4:
         someStuff = True

Upvotes: 1

gabe
gabe

Reputation: 2511

This is a strange issue with the way global variables work in python.

This change should work:

someStuff = False
def spawn():
    print(someStuff)
    if( 3==4):
       global someStuff
       someStuff = True  
while (someStuff==False):
    spawn()

For more on why this happens this way: read this

Upvotes: 0

Related Questions