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).
In function
torneio
, what happens ifcanditado_1
is greater than 0.5? Does not enter thewhile
and a variable is returned that has not been defined. (Note: I would not be a candidate instead of a candidate?)– Woss
Yes it’s candidate, misspelled, Thanks for the remark! I’ve corrected.
– Danilo
I understand your explanation. But how do I solve this problem?
– Danilo