Search code examples
pythonrandom

what code is more efficient for me to write if i want to be sure that in no way the random choices in my code gets repeated?


so here is the code

import random
choices = [1,2,3,4,5]
choice1=random.choice(choices)
choice2=random.choice(choices)
if choice1==choice2 :
    choice2 =random.choice(choices)

so from my knowledge, this code works for one time (like what if the second time also the choice got as same ) and if i want to use while , i cant say (while choice1 != choice2)cause in the order of code they should be before defined so what is your solution (also if you feel explaining in more detail problems to level of my conceptualization it would be very appreciated )


Solution

  • you can also try with a while, to keep generating a new random number for choice2 until is different from choice1

    import random
    choices = [1,2,3,4,5]
    choice1=random.choice(choices)
    choice2=random.choice(choices)
    while choice1==choice2 :
        choice2 =random.choice(choices)