Python: IndexError: list index out of range

前端 未结 3 1048
灰色年华
灰色年华 2020-12-14 12:07

I think I have my program completed, but... it doesn\'t work. I\'m trying to write a program that simulates a lottery game, but when I try to check the user\'s guesses again

3条回答
  •  时光取名叫无心
    2020-12-14 12:50

    Here is your code. I'm assuming you're using python 3 based on the your use of print() and input():

    import random
    
    def main():
        #random.seed() --> don't need random.seed()
    
        #Prompts the user to enter the number of tickets they wish to play.
    
        #python 3 version:
        tickets = int(input("How many lottery tickets do you want?\n"))
    
        #Creates the dictionaries "winning_numbers" and "guess." Also creates the variable "winnings" for total amount of money won.
        winning_numbers = []
        winnings = 0
    
        #Generates the winning lotto numbers.
        for i in range(tickets * 5):
            #del winning_numbers[:] what is this line for?
            randNum = random.randint(1,30)
            while randNum in winning_numbers:    
                randNum = random.randint(1,30)
            winning_numbers.append(randNum)
    
        print(winning_numbers)
        guess = getguess(tickets)
        nummatches = checkmatch(winning_numbers, guess)
    
        print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")
    
        winningRanks = [0, 0, 10, 500, 20000, 1000000]
    
        winnings = sum(winningRanks[:nummatches + 1])
    
        print("You won a total of",winnings,"with",tickets,"tickets.\n")
    
    
    #Gets the guess from the user.
    def getguess(tickets):
        guess = []
        for i in range(tickets):
            bubble = [int(i) for i in input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split()]
            guess.extend(bubble)
            print(bubble)
        return guess
    
    #Checks the user's guesses with the winning numbers.
    def checkmatch(winning_numbers, guess):
        match = 0
        for i in range(5):
            if guess[i] == winning_numbers[i]:
                match += 1
        return match
    
    main()
    

提交回复
热议问题