+ 1
How to change variables in functions (python)
When I make a code like: n = 0 def add_1 (): n += 1 print(n) It would give an UnboundLocalError. How do I fix this?
2 Answers
+ 10
You need to call the function, which needs a parameter and should return a value. This works:
n = 0
def add_1(n):
n += 1
return n
print(add_1(n))
+ 4
You can also add a global declaration in the function before using it.
global n.
However in real world programs usage of global variables is discouraged.