0
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.

Dr C
  • 150
  • 3
  • 9
  • Is the question about why you're getting this error? I explained that in my answer. But this code as is just gets you in an infinite loop printing `False`... – gabe Sep 17 '14 at 17:19
  • Also, the issue isn't the `if` statement but the part where you define `someStuff = True` in `spawn`. If you take out that definition, then `someStuff` just refers to the global variable. – gabe Sep 17 '14 at 17:22
  • possible duplicate of [Python variable scope error](http://stackoverflow.com/questions/370357/python-variable-scope-error) – chepner Sep 17 '14 at 17:33

3 Answers3

1

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.

Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
1

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
khelwood
  • 55,782
  • 14
  • 81
  • 108
0

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

Community
  • 1
  • 1
gabe
  • 2,521
  • 2
  • 25
  • 37