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).