0

I have my code as below.

def test():
   print num1
   print num
   num += 10

if __name__ == '__main__':
   num = 0
   num1 = 3
   test()

When executing the above python code I get the following output.

3 
Traceback (most recent call last):
File "<stdin>", line 3, in <module>
File "<stdin>", line 2, in test
UnboundLocalError: local variable 'num' referenced before assignment

I do not know why particularly num is not available in test method. It is very weird for me and i did not face this yet before.

Note: I am using python 2.7.

9
  • 2
    Assuming you indent properly, this code works. Please check again that you show the exact code that throws this error, you may have a typo somewhere. Commented Nov 18, 2013 at 12:08
  • @delnan I used the num variable in a place as in my last edit. Hope it makes the error in the code. Can you look the above code? Commented Nov 18, 2013 at 12:53
  • possible duplicate of UnboundLocalError in Python Commented Nov 18, 2013 at 12:54
  • See, now it's easy. If you'd had included the right code (or even just the exception message) from the start, you would have gotten your answer an hour sooner ;-) Commented Nov 18, 2013 at 12:56
  • Cool, your edit brought me a downvote because my answer is no longer valid. Commented Nov 19, 2013 at 11:18

2 Answers 2

1

num appears in an assignment statement inside the definition of the test. This makes num a local variable. Since scope determination is made at compile time, num is a local variable even in the print statement that precedes the assignment. At that time, num has no value, resulting in the error. You need to declare num as global if you want to access the global value. num1 does not have this problem, since you never try to assign to it.

def test():
    global num
    print num1
    print num
    num += 10
Sign up to request clarification or add additional context in comments.

Comments

1

Since you're assigning to num inside the test function, python considers it to be a local variable. This is why it complains that you are referencing to a local variable before assigning it.

You can fix this by explicitly declaring num to be global:

def test():
    global num
    print num1
    print num
    num += 10

if __name__ == '__main__':
    num = 0
    num1 = 3
    test()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.