random.choice() in Python does not work correctly.
I have the following function, but the following happens when called:
def Randomswitch():
thechosenone = random.choice(range(0, 2))
if (thechosenone == 0):
return "WIN"
if (thechosenone == 1):
return "LOSE"
Randomswitch()
When Randomswitch is called it only returns WIN every time it’s called.
I am breaking my head trying to figure this out.
Can anyone help me please?
>Solution :
Seems to be working pretty well, have you tried only a few times? Let’s try 10,000 times and count the occurrences:
import random
from collections import Counter
def Randomswitch():
thechosenone = random.choice(range(0, 2))
if (thechosenone == 0):
return "WIN"
if (thechosenone == 1):
return "LOSE"
Counter(Randomswitch() for i in range(10000))
output:
Counter({'LOSE': 4980, 'WIN': 5020})
Seems pretty decent 😉
improving the code
That said, you code can be improved, why don’t you just pass the values to chose from to random.choice?
def Randomswitch():
return random.choice(['WIN', 'LOSE'])