1

I'm not sure why it's not working when I declare a global variable...

first_read = True

def main():

    if (first_read == True):
        print "hello world"
        first_read = False

    print 'outside of if statement'

if __name__ == '__main__':
    main()

My traceback shows the following error:

Traceback (most recent call last):
   File "true.py", line 12, in <module>
      main()   
   File "true.py", line 5, in main
     if (first_read == True): 
UnboundLocalError: local variable 'first_read' referenced before assignment
1

2 Answers 2

3

You have to define variable as global:

first_read = True

def main():
    global first_read
    if (first_read == True):
       print "hello world"
       first_read = False

    print 'outside of if statement'

if __name__ == '__main__':
    main()
Sign up to request clarification or add additional context in comments.

1 Comment

Just curious... I also have a global variable: 'ntw_device = []' declared.. But I didn't have to specify global ntw_device to use it... Why is that? Is it different for lists?
2

In def main you should declare a global variable like this:

global first_read

this will use first_read as global variable in main function.

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.