vendredi 23 avril 2021

Why does random.choice() sometimes not make any choice?

I'm trying to create some logic that will reliably choose between two things. But the following code seems to have some serious bug in it because often there is no choice made.

import random
while True:
    if random.choice([0, 1]) == 0:
        print("Right")
    elif random.choice([0, 1]) == 1:
        print("Left")
    else:
        print("Why do we ever reach the else?")

The output looks like this:

$ python3 random.choice.broken.py 
Why do we ever reach the else?
Why do we ever reach the else?
Left
Why do we ever reach the else?
Left
Right
Left
Left
Why do we ever reach the else?
Why do we ever reach the else?
Right
Why do we ever reach the else?
Left
Right
Right
Why do we ever reach the else?
Left
Right
Left
Left
Right
Left
Right
Right
Right
Why do we ever reach the else?
Left
Why do we ever reach the else?
Why do we ever reach the else?
Right

I'm sure there must be a reasonable explanation. But I can't find it online or in the documentation. Thanks.




Aucun commentaire:

Enregistrer un commentaire