4
I have the following code below:
#!/usr/bin/python3
# VARIÁVEIS
variavel = 0
def valores():
if ( variavel == 0):
variavel = 100
elif (variavel == 1):
variavel = 200
elif (variavel == 2):
variavel = 300
elif (variavel == 3):
variavel = 400
valores()
The following error appears:
Traceback (most recent call last):
File "teste.py", line 25, in <module>
valores()
File "teste.py", line 9, in valores
if ( variavel == 0):
UnboundLocalError: local variable 'variavel' referenced before assignment
Why does this happen? Wasn’t the variable supposed to be global in this case? How to solve this, so that I have a variable in which I need to modify and access through various functions?
May I suggest changing the title to "how to handle global variables in Python"?
– Jefferson Quesado
Related: What’s the difference between global and nonlocal in Python?
– Woss