[Tutor] 6 random numbers
Steven D'Aprano
steve at pearwood.info
Mon Oct 17 01:33:16 CEST 2011
ADRIAN KELLY wrote:
> hello all,
> anyone know how i would go about printing 6 random numbers, i know i could copy and paste 6 times (which would work) but i was thinking about a while loop, ie. while lottery_numbers.count is <7.
> Is it possible to code this? is it possible to count random variables? i am trying to keep the program as simple as possible, cheers
>
> any help would be welcome,
>
> import random
> lottery_numbers=random.randrange(1,42)
> print lottery_numbers
Whenever you want to do something repeatedly, a for-loop or while-loop
is usually the answer. If you know how many times you need to do it, use
a for-loop:
for i in range(6):
print random.randrange(1,42)
If you don't know how many times, use a while-loop:
total = 0
while total < 100:
total += random.randrange(1,42)
print total
If you want to collect the intermediate results, either store them in a
list:
results = []
for i in range(6):
results.append(random.randrange(1,42))
or use a list comprehension, which is syntactic sugar for a for-loop:
results = [random.randrange(1,42) for i in range(6)]
--
Steven
More information about the Tutor
mailing list