Issue using If statement in Python

Question:

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.

Asked By: Paterau Bogdan

||

Answers:

break will, well, break out of the loop.

Use continue to continue the loop from the top again, and make sure you pick the first (and only) element returned from random.Choices:

while I < 6:
    y = random.choices(range(1,50))[0]
    if y in z:
        continue # skip to next iteration and continue
    z.append(y)
    I += 1

Or better, use random.randint() to pick the integer instead of expanding the full range every time:

while I < 6:
    y = random.randint(1,50)
    if y in z:
        continue # skip to next iteration and continue
    z.append(y)
    I += 1
Answered By: Mathias R. Jessen

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)
Answered By: Parsa

You should do multiple things:

  1. use random.randint()
  2. use .append() for arrays and not +=
  3. use continue instead of break

Your code can look like this:

import random
I = 0
z = []
while I < 6:
    y = random.randint(1,50)
    if y in z:
        continue
    z.append(y)
    I += 1
print(z)
Answered By: alanturing

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.

Answered By: deceze

You can also use walrus (:=) operator and check if y is not in z:

from random import randint
z = list()
while len(z) < 6:
    if (y := randint(1,50)) not in z: z += [y]
print(z)
Answered By: Arifa Chan
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.