Reputation: 514
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
Upvotes: 1
Views: 120
Reputation: 84
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.
Upvotes: 2
Reputation: 436
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()
Upvotes: 3