Generating a list of random integers in python 3 -
i getting indexerror: list assignment index out of range error when trying run program. index appears fine (0 through 8) , don't think .append needed since equal sign assign random value each pass. missing?
import random #the main function. def main(): #welcome message. print("welcome lottery number generator program!") print() #explain program does. print("note: program randomly generate 7 digit lottery number , display screen. ") print("________________________________________________________________________________________________") print() print() #call generatenumbers function , store returned list in variable lotterynumbers. lotterynumbers = generatenumbers() #call printlottery function , pass lotterynumbers list argument. printlottery(lotterynumbers) #the generatenumbers function generated 7 random digits between 0 , 9 stores them in list , returns list. def generatenumbers(): #a list variable hold empty list. lotterynumbers = [] #declare , set loop counter 0. index = 0 index in range (0,8): lotterynumbers[index] = random.randrange(0,10) index += 1 return lotterynumbers def printlottery(lotterynumbers): print("here 7 lucky numbers: {}".format(lotterynumbers)) #end main main()
by initializing list
lotterynumbers = []
it has 0 elements. with
lotterynumbers[index] = random.randrange(0,10)
you try access 1st, 2nd, .. , nth element of list. code not insert elements list. avoid there serveral approaches.
- create dict instead of list. dict creates nonexistent elements:
lotterynumbers = {}
- preinitialize list 8 elements:
lotterynumbers = [0,0,0,0,0,0,0,0]
- or
lotterynumbers = list(range(8))
- but preferable variant should use append:
lotterynumbers.append(random.randrange(0,10))
Comments
Post a Comment