Why is the variable not modified?

Asked

Viewed 477 times

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?

2 answers

5

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 receive it as 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)

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • About using as parameter and reassign: Protection against competition? Elegance? Or is there anything else I haven’t noticed?

  • 1

    @Jeffersonquesado One of the points is maintenance. The variable does not have the shape changed value magic when you analyze the code flow.

  • @Jeffersonquesado And also because that’s how he did it. In real code I would do it in a very different way :)

5


To modify a variable you need to set it as global or take it as 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 to 100, but the print result will be 100 and not 'test new value' because within the text function, "variable" is local.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.