pythonrandomnumbersnon-repetitive

Making 6 different random Numbers


I'm not that good at coding right now, i am trying to improve and learn. ATM i was trying to write a code that randomly picks 6 non-repeating numbers, but i fail at it. what should i do?

import random

a = random.randint(1, 100)
b = random.randint(1, 100)
c = random.randint(1, 100)
x = random.randint(1, 100)
y = random.randint(1, 100)
z = random.randint(1, 100)

outa = b, c, x, y, z
outb = a, c, x, y, z
outc = a, b, x, y, z
outx = a, b, c, y, z
outy = a, b, c, x, z
outz = a, b, c, x, y

all = a, b, c, x, y, z

while a in outa or b in outb or c in outc or x in outx or y in outy or z in outz:
    if a in outa:
        a = random.randint(1,100)
    elif b in outb:
        b = random.randint(1,100)
    elif c in outc:
        c = random.randint(1,100)
    elif x in outx:
        x = random.randint(1,100)
    elif y in outy:
        y = random.randint(1,100)
    elif z in outz:
        z = random.randint(1,100)

print(all)

Solution

  • all = a, b, c, x, y, z
    

    Things like that creates a tuple of values. So at the time the line executes, that tuple has fixed values inside and cannot be changed. It especially does not change when you update one of the variables you originally used to construct it. So you cannot use all for the final result, or the outX tuples to check for any duplicates because they are fixed and will not update.

    In order for your code to work, you would have to recreate all those tuples in every iteration of your while loop. But in general, you will quickly notice that having those explicit variables is not a good idea.

    If you want to keep using randint, then you could just generate one number at a time, and “reroll” whenever you encounter a number you already have:

    numbers = []
    while len(numbers) < 6:
        num = random.randint(1, 100)
        if num not in numbers:
            numbers.append(num)
    

    I’m using a list here, which is a mutable data structure to collect multiple values (compared to the tuple, which is immutable).

    You can also use random.sample here which offers an even easier way to get any number of unique values from a range of numbers:

    numbers = random.sample(range(1, 100), 6)