I would like to increase the value of variable count
by 1, but only when the function printcount
is called in the CODE below.
global count
count = 0
def PrintCount():
count += 1
print count
PrintCount()
When I run this code I get the following error:
Traceback (most recent call last):
File "C:\Users\Cross\Desktop\Code.py", line 8, in <module>
PrintCount()
File "C:\Users\Cross\Desktop\Code.py", line 5, in PrintCount
count += 1
UnboundLocalError: local variable 'count' referenced before assignment
I would like to know why this is happening and how to fix it.
Thank You.
Use global
keyword inside the function to access (especially modify) the global variable count
:
def PrintCount():
global count # <----
count += 1
print count
Declaring global outside the function has no effect.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments