Unboundlocalerror: local variable 'adversario_1' referenced before assignment

Asked

Viewed 5,762 times

1

I have the following code:

def aleatorio():
    from random import random
    a = random()
    return a
def torneio():
    canditado_1 = aleatorio()
    while canditado_1 <= 0.5:
        canditado_1 = aleatorio()
        if canditado_1 > 0.5:
            adversario_1 = canditado_1
    return adversario_1

When I run the code shows the error:

Unboundlocalerror: local variable 'adversario_1' referenced before assignment

I’ve tried everything. I know it’s an attribution error, but I can’t fix it.

What I have to do to fix?

  • In function torneio, what happens if canditado_1 is greater than 0.5? Does not enter the while and a variable is returned that has not been defined. (Note: I would not be a candidate instead of a candidate?)

  • Yes it’s candidate, misspelled, Thanks for the remark! I’ve corrected.

  • I understand your explanation. But how do I solve this problem?

1 answer

3


The problem is in the function torneio. The value of the variable is returned adversario_1, but this is defined only within the while. If, in the first line, candidato_1 = aleatorio(), has already been drawn a value greater than 0.5, the while is ignored and a variable is returned that has never been defined. A very simple logical error to fix: just put the assignment to the variable adversario_1 outside the while. Behold:

def torneio():
    candidato_1 = aleatorio()

    while candidato_1 <= 0.5:
        candidato_1 = aleatorio()

    adversario_1 = candidato_1

    return adversario_1

In this test run the function 100 times and put to display an error message if the returned value was less than or equal to 0.5, see that nothing is displayed, then we have the guarantee that always the value will be greater than 0.5.

A slightly better code, implementing the same logic, would be:

from random import random

def torneio():
    while True:
        candidato_1 = random()
        if candidato_1 > 0.5:
            return candidato_1

The result is exactly the same, since the function aleatorio can be replaced directly by random and the while previous by the infinite loop defined by while True. This case is more appropriate as it makes only one call to the function random, while previously needed to call twice (code redundancy).

  • Your explanation was extremely didactic and solved my problem. You are to be congratulated!!

Browser other questions tagged

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