I wanna make 6 different & random numbers in Python.
So I coded it like this:
from random import *
def make_lotto():
n = randrange(1, 46)
return n
lotto = []
while True:
if make_lotto() != randrange(1, 46):
lotto.append(randrange(1, 46))
if len(lotto) == 6:
break
lotto.sort()
print(lotto)
Although I defined if make_lotto() != randrange(1, 46)
, the same number is still printed more than once.
I think if make_lotto() != randrange(1, 46)
code is not defined.
How could I revise this code?
CodePudding user response:
The conventional way of doing something like this is to make an empty list and keep filling the list (under the conditions) until it is complete.
So, you could do this:
import random
r = []
while len(r) < 6:
x = random.randrange(1,46)
if x in r:
pass
else:
r.append(x)
print(r)
result (random list that keeps changing):
[44, 16, 14, 27, 11, 34]
CodePudding user response:
if make_lotto() != randrange(1,46)
The numbers generated by the expressions on both sides are random, so, make_lotto() != randrange(1,46)
is invalid.