Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue using If statement in Python

Tags:

python

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.

like image 648
Paterau Bogdan Avatar asked Feb 19 '26 19:02

Paterau Bogdan


2 Answers

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.

like image 123
deceze Avatar answered Feb 22 '26 08:02

deceze


Check out this code, it works pretty well for me.

  1. since choices returns a list, I used choice instead to return a number.
  2. break stops the code so I used continue instead.
  3. variable 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)
like image 24
Parsa Avatar answered Feb 22 '26 08:02

Parsa