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

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -