UnboundLocalError: local variable 'adversary_1' referenced before assignment

0

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 it displays the error:

  

UnboundLocalError: local variable 'adversary_1' referenced before assignment

I have tried everything. I know it's an assignment error, but I can not resolve it.

What do I have to do to resolve?

    
asked by anonymous 21.04.2017 / 01:12

1 answer

3

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

def torneio():
    candidato_1 = aleatorio()

    while candidato_1 <= 0.5:
        candidato_1 = aleatorio()

    adversario_1 = candidato_1

    return adversario_1

In this test I ran the function 100 times and put it to display an error message if the returned value was less than or equal to 0.5 , see that nothing is displayed, so we are guaranteed that the value will always 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 aleatorio function can be replaced directly by random and while by the infinite loop defined by while True . This case is most appropriate because it only calls the random function, whereas before it needed to call twice (code redundancy).

    
21.04.2017 / 01:33