I am trying to create a code to simulate a lottery game. I need to check if one of the generated numbers already has been generated before

I already have a working code but I noticed that sometimes 2 or more of the same numbers would be generated in a list and therefore mess up the whole game. I am not very experienced in python so I have no clue on how to check if the number has been used on the list and if so, on how to generate a new, unused one!

I need a new piece of code to check for this problem and if it happens, to regenerate the number.
Here is my existing code:

import random

luckynumber = []
inputnumber = []

correct_numbers = 0

print('Welcome to the game!')
print('Please insert 6 numbers from 1 to 49:')

for number in range(0, 6):
  randomnumber = random.randint(1, 49)
  luckynumber.append(randomnumber)

for number in range(0, 6):
  player_number = int(input())
  inputnumber.append(player_number)

for correctnumber in luckynumber:
  for player_number in inputnumber:
    if player_number == correctnumber:
      correct_numbers = correct_numbers + 1

print(f'You gessed {correct_numbers} correct numbers!')
print(f'Original correct numbers: {luckynumber}')

>Solution :

random.sample will give you a sample of k random elements from a population, with each element guaranteed to be different. So you can do that and not have to worry about finding and replacing duplicates.

Link to standard library documentation

In your code you’d do:

luckynumber = random.sample(range(1, 50), 6)

Note that randint(1, 49) gives you numbers between 1 and 49 inclusive, but range gives a range of numbers that excludes that last element. So here we have range(1, 50) to select from the numbers 1-49 inclusive.

Leave a Reply