Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: IndexError: list index out of range

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 against the number of guesses on the ticket, I get an error that tells me the "list index is out of range". I think it has something to do with the part of the code where I assign the random digits to "a," "b", "c", etc. But I'm not sure.

Here is the code in it's entirety:

import random

def main():
random.seed()

#Prompts the user to enter the number of tickets they wish to play.
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 = []
guess = []
winnings = 0

#Generates the winning lotto numbers.
for i in range(tickets):
    del winning_numbers[:]

    a = random.randint(1,30)
    while not (a in winning_numbers):
        winning_numbers.append(a)

    b = random.randint(1,30)
    while not (b in winning_numbers):
        winning_numbers.append(b)

    c = random.randint(1,30)
    while not (c in winning_numbers):
        winning_numbers.append(c)

    d = random.randint(1,30)
    while not (d in winning_numbers):
        winning_numbers.append(d)

    e = random.randint(1,30)
    while not (e in winning_numbers):
        winning_numbers.append(e)

    print(winning_numbers)
    getguess(guess, tickets)
    nummatches = checkmatch(winning_numbers, guess)

    print("Ticket #"+str(i+1)+": The winning combination was",winning_numbers,".You matched",nummatches,"number(s).\n")

    if nummatches == 0 or nummatches == 1:
        winnings = winnings + 0
    elif nummatches == 2:
        winnings = winnings + 10
    elif nummatches == 3:
        winnings = winnings + 500
    elif nummatches == 4:
        winnings = winnings + 20000
    elif nummatches == 5:
        winnings = winnings + 1000000

print("You won a total of",winnings,"with",tickets,"tickets.\n")

#Gets the guess from the user.
def getguess(guess, tickets):
del guess[:]

for i in range(tickets):
    bubble = input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split(" ")
    guess.append(bubble)
print(bubble)

#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 = match+1

return match

main()

And here is the error I get:

Traceback (most recent call last):
  File "C:\Users\Ryan\Downloads\Program # 2\Program # 2\lottery.py", line 85, in <module>
    main()
  File "C:\Users\Ryan\Downloads\Program # 2\Program # 2\lottery.py", line 45, in main
   nummatches = checkmatch(winning_numbers, guess)
File "C:\Users\Ryan\Downloads\Program # 2\Program # 2\lottery.py", line 79, in checkmatch
    if guess[i] == winning_numbers[i]:
IndexError: list index out of range
like image 368
Ryan W Avatar asked Feb 13 '12 05:02

Ryan W


People also ask

How do you handle list index out of range?

To solve this error we will take the index of the last value of the list and then add one then it will become the exact value of length.

What causes IndexError Python?

An IndexError means that your code is trying to access an index that is invalid. This is usually because the index goes out of bounds by being too large. For example, if you have a list with three items and you try to access the fourth item, you will get an IndexError.

What does IndexError list index out of range mean?

You'll get the Indexerror: list index out of range error when you try and access an item using a value that is out of the index range of the list and does not exist. This is quite common when you try to access the last item of a list, or the first one if you're using negative indexing.

How do you prevent index out of range error?

This index error is triggered when indexing a list using a value outside of its range of indexes. The best way to avoid it is by carefully considering what range of indexes a list might have, taking into account that list indexes start at zero instead of one.


1 Answers

As the error notes, the problem is in the line:

if guess[i] == winning_numbers[i]

The error is that your list indices are out of range--that is, you are trying to refer to some index that doesn't even exist. Without debugging your code fully, I would check the line where you are adding guesses based on input:

for i in range(tickets):
    bubble = input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split(" ")
    guess.append(bubble)
print(bubble)

The size of how many guesses you are giving your user is based on

# Prompts the user to enter the number of tickets they wish to play.
tickets = int(input("How many lottery tickets do you want?\n"))

So if the number of tickets they want is less than 5, then your code here

for i in range(5):

if guess[i] == winning_numbers[i]:
    match = match+1

return match

will throw an error because there simply aren't that many elements in the guess list.

like image 146
simchona Avatar answered Oct 28 '22 23:10

simchona