mardi 25 juillet 2017

Generating a list of random integers in python 3

I am getting a IndexError: list assignment index out of range error when trying to run this program. My index appears to be fine (0 through 8) and I don't think .append is needed since the equal sign assign the random value each pass. What am I missing?

import random

#The main function.
def main():

  #Welcome message.
  print("Welcome to the lottery number generator program!")
  print()

  #Explain what the program does.
  print("Note: This program will randomly generate a 7 digit lottery number and display it to the screen. ")
  print("________________________________________________________________________________________________")
  print()
  print()

  #Call the generateNumbers function and store its returned list in variable lotteryNumbers.
  lotteryNumbers = generateNumbers()

  #Call the printLottery function and pass the lotteryNumbers list as argument.
  printLottery(lotteryNumbers)


#The generateNumbers function generated 7 random digits between 0  and 9 stores them in a list and returns the list.
def generateNumbers():

  #A list variable to hold empty list.
  lotteryNumbers = []

  #Declare and set loop counter to 0.
  index = 0

  for index in range (0,8):
    lotteryNumbers[index] = random.randrange(0,10)
    index += 1
  return lotteryNumbers


def printLottery(lotteryNumbers):
  print("Here are the 7 lucky numbers: {}".format(lotteryNumbers))

#End main
main()




Aucun commentaire:

Enregistrer un commentaire