Why is the variable unchanged?

2

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 occur? Was not the variable to be global in this case? How do I solve this, so that I have a variable in which I need to modify and access through multiple functions?

    
asked by anonymous 26.02.2018 / 20:00

2 answers

3

To change a variable you need to set it to global or get it as a parameter.

variavel = 0

def valores():

    global variavel

    if (variavel == 0):
        variavel = 100

    elif (variavel == 1):
        variavel = 200


def texto():
    variavel = 'teste novo valor'


valores()
texto()
print(variavel)

This code allows you to change the value of "variable" and change it to 100, but the result of the print will be 100 and not 'test new value' because within the text function, "variable" is local.

    
26.02.2018 / 20:34
3

If you declare that the variable is external (global) it works, but do not do this, if you need to work with a value that comes from outside get it as a parameter.

variavel = 0

def valores():
    global variavel
    if (variavel == 0):
        variavel = 100
    elif (variavel == 1):
        variavel = 200
    elif (variavel == 2):
        variavel = 300
    elif (variavel == 3):
        variavel = 400

valores()

Prefer to do

def valores(variavel):
    if (variavel == 0):
        variavel = 100
    elif (variavel == 1):
        variavel = 200
    elif (variavel == 2):
        variavel = 300
    elif (variavel == 3):
        variavel = 400
    return variavel

variavel = 0
variavel = valores(variavel)
    
26.02.2018 / 20:30