Question

Okay, no more questions after this:

import random

lotto = [0, 0, 0, 0, 0, 0, 0, 0]
index = 0

while index <= 6:
    lotto[index] = random.randrange(1, 9)
    index = index + 1
    print("Lotto number",index,"is",lotto[index],"!")

I cannot seem to find what is up with why these sequence elements will not be modified. The index and the sequence are handled properly but the lotto[index] = random.randrange(1, 9) line seems to be useless. It doesn't change anything in the sequence at all. I know I'm missing something but I've been staring at this thing for a long time now and just cannot see what I'm screwing up. I've changed the elements and it outputs everything properly it just won't change the sequence elements. Halps?

Était-ce utile?

La solution

You are always referring to the next element while printing. Just swap the print line with the increment line like this

print("Lotto number",index,"is",lotto[index],"!")
index = index + 1

When you print something like this, you can use format function, like this

print("Lotto number {} is {} !".format(index, lotto[index]))

Apart from that, you can use a for loop and range function, like this

for index in range(7):
    lotto[index] = random.randrange(1, 9)
    print("Lotto number", index, "is", lotto[index], "!")

range function will give the values from 0 to 6, one at a time, on each iteration.

Even better, you can create a new list using list comprehension, like this

lotto = [random.randrange(1, 9) for index in range(7)]
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top