I am creating a 'Euromillions Lottery generator' just for fun and I keep getting the same numbers printing out. How can I make it so that I get random numbers and never get the same number popping up:
from random import randint
numbers = randint(1,50)
stars = randint(1,11)
print "Your lucky numbers are: ", numbers, numbers, numbers, numbers, numbers
print "Your lucky stars are: " , stars, stars
The output is just:
>>> Your lucky numbers are: 41 41 41 41 41
>>> Your lucky stars are: 8 8
>>> Good bye!
How can I fix this?
Regards
You are generating one number then printing that out several times.
Generate several numbers instead:
print "Your lucky numbers are: ", randint(1,50), randint(1,50), randint(1,50), randint(1,50), randint(1,50)
or generate a list:
numbers = [randint(1,50) for _ in range(5)]
print "Your lucky numbers are: ", ' '.join(numbers)
or better still, generate all permissible numbers (using range()
then pick a sample from that:
possible_numbers = range(1, 51) # end point is not included
numbers = random.sample(possible_numbers, 5)
print "Your lucky numbers are: ", ' '.join(map(str, numbers))
Now numbers
is guaranteed to consist of entirely unique numbers.
The numbers
variable does not magically update every time you print it because it refers only to the result of random.randint(1, 50)
.
Set up a set of numbers then shuffle and slice the set.
from random import shuffle
numbers = list(range(1,51))
shuffle(numbers)
draw = numbers[:6]
print(draw)
numbers = randint(1,50)
assigns one random number to a variable. And you repeatedly use this one random number. Same goes for stars
Try this instead:
print "Your lucky numbers are: ", randint(1,50), randint(1,50), randint(1,50), randint(1,50), randint(1,50)
Or you can create a list of numbers and get a random sample:
numbers = range(1,50)
print "Your lucky numbers are: ", ' '.join(map(str, random.sample(numbers, 5)))
You should call randint
5 times for your lucky numbers. You only call it once, and display the result 5 times.
You can use
random.sample(range(range_to_which_random_be_generated), number_of_numbers_to_generate)
example
random.sample(range(50),6)
would generate 6 different numbers in range 0 to 49
One way i would suggest is to put the generated numbers in a list, and check if the next number is not in the list list before adding it to the list
numbers=[randint(1,50)]
i=1
while i<n: # n is the number of random numbers you want to generate
x=randint(1,50)
if not x in numbers:
i+=1
numbers.append(x)
The problem in your code is that you generate only a single random number and print it four times
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.