1

I created a random lottery number generator for COP1000 that passes a random number 0-9 to an array of 7 integers. However, when I print the array, I get the same output 7 times. It may be a problem with one of the loops but I am unsure of where it is coming from. Any help would be greatly appreciated.

Here is the code:

import random
print("Seven lucky numbers; are you ready?")

numbers = [0,0,0,0,0,0,0]



index = 0
while index<len(numbers):
    numbers[index] = random.randint(0,9)
    index = index + 1

for n in numbers:
    print("\nYour random lottery number is:")
          print(numbers[0],numbers[1],numbers[2],numbers[3],numbers[4],numbers[5],numbers[6])
Shamar
  • 13
  • 1
  • 3

2 Answers2

0

With this:

for n in numbers:
    print("\nYour random lottery number is:")
    print(numbers[0],numbers[1],numbers[2],numbers[3],numbers[4],numbers[5],numbers[6])

You are printing the entire list in a loop. Either loop over the list or print the whole thing, but don't do both. The easiest way to solve this and produce your desired output is to replace the above code with the following:

print("\nYour random lottery number is:")
print(*numbers)
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
0

As stated by TigerhawkT3 it seems you are confused with how to print out the values once you have pushed them into your array. (Also you would not want to put the initial print statement inside the loop unless you want it to print for every item in the list)

This link shows how to use for loops in different capacities. One way to solve your problem would be:

print("\nYour random lottery numbers are:")
for n in numbers: 
  print n

If you want to loop through and print out each value with some kind of string in front of all or 1 item you can use:

print("\nYour random lottery numbers are:")
for index in range(len(numbers)):
  if index == len(numbers) - 1:
    print "power number: ", numbers[index]
  else:
    print index, ' : ', numbers[index]

Lastly if you are just trying to print all the numbers with a delimiter in one print statement then seems like this maybe a duplicate of this question or this one where the solution was:

 print("\nYour random lottery numbers are:")
 print ', '.join(map(str, numbers))
Community
  • 1
  • 1
Alan DeLonga
  • 454
  • 1
  • 10
  • 27
  • Hello Alan, I really appreciate your response. I am using Python 3.6, so my print statement for that last example looks like this: print("\nYour random lottery numbers are:") print(", ".join(numbers)) However, I got this error stating that .join() expects a string: TypeError: sequence item 0: expected str instance, int found Would I have to change numbers=[] to strings? – Shamar Mar 02 '17 at 03:50
  • I updated the answer to use map(str, numbers) to convert the array elements to strings, per this post: http://stackoverflow.com/questions/3590165/joining-a-list-that-has-integer-values-with-python – Alan DeLonga Mar 03 '17 at 22:19