15
votes

I've got something here, but I can't get it working how I like it:

def nested_loops():
    import random
    option1 = random.randint(1, 3)
    option2 = random.randint(1, 3)
    option3 = random.randint(1, 3)

The bit above generates numbers, but they may be the same. The below code this should fix that, but it doesn't, but it just seems to decrease the likelihood:

while option1 == option2:
    option1 = random.randint(1,3)
    while option1 == option3:
        option1 = random.randint(1, 3)
        while option2 == option3:
            option2 = random.randint(1, 3)

print(option1)
print(option2)
print(option3)

It is fairly obvious it just prints them.

2
Agree that based on the accepted answer this is a duplicate, but feel the need to point out that import random;alist = [x+1 for x in range(3)]; random.shuffle(alist) will handle the case where the list is 1 to N (in this case 3) - Foon

2 Answers

32
votes

You can use random.sample to get any amount of unique 'random' items from an iterable- there is no need to use nested loops:

>>> option1, option2, option3 = random.sample(range(1, 4), 3)
>>> option1, option2, option3
(3, 1, 2)
1
votes

The bug in your code is that if option1 and option2 are different, the first while won't be entered, and you won't examine if any of them are equal to option3.