Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

random.choice() not selecting all possibilities

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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'])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading