Input:
import random
I = 0
z = []
while I < 6:
y = random. Choices(range(1,50))
if y in z:
break
z += y
I += 1
print(z)
Output: [8, 26, 8, 44, 31, 22]
I'm trying to make a Lotto numbers generator but I can't make the code to generate 6 numbers that do not repeat. As you can see in the Output 8 is repeating.
I'm not clear why in the If statement the code does not check if the random y variable is already in the z list.
Use random.sample:
>>> from random import sample
>>> sample(range(1, 50), k=6)
[40, 36, 43, 15, 37, 25]
It already picks k unique items from the range.
Check out this code, it works pretty well for me.
I can be omitted using len(z) in while statement. (as suggested by Mime).
import random
# I = 0
z = []
while len(z) < 6: # instead of I < 6: (Thanks to Mime)
y = random.choice(range(1,50)) # edit: you can also use random.randint(1,49) instead of choice.
if y in z:
continue
z.append(y) # instead of z += [y] (Thanks to deceze)
# I += 1
print(z)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With