+ 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?

27th Feb 2018, 6:54 PM
Zack
Zack - avatar
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))
27th Feb 2018, 7:08 PM
David Ashton
David Ashton - avatar
+ 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.
27th Feb 2018, 7:47 PM
Ravi Chandra Enaganti
Ravi Chandra Enaganti - avatar