Python: IndexError: list index out of range
Solution 1
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.
Solution 2
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()
Solution 3
I think you mean to put the rolling of the random a,b,c, etc within the loop:
a = None # initialise
while not (a in winning_numbers):
# keep rolling an a until you get one not in winning_numbers
a = random.randint(1,30)
winning_numbers.append(a)
Otherwise, a
will be generated just once, and if it is in winning_numbers
already, it won't be added. Since the generation of a
is outside the while
(in your code), if a
is already in winning_numbers
then too bad, it won't be re-rolled, and you'll have one less winning number.
That could be what causes your error in if guess[i] == winning_numbers[i]
. (Your winning_numbers
isn't always of length 5).
Ryan W
Updated on July 05, 2022Comments
-
Ryan W almost 2 years
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
-
Joel Cornett about 12 yearsThis will code will only run if a is NOT in winning_numbers. In other words, if there is a repeat, no number will be appended. Remember, while checks the run condition before running.
-
Joel Cornett about 12 yearsActually, his errors are being caused a little earlier down the line. Based on his input statement,
bubble
is a list of strings. This list then gets appended toguess
. Soguess
would look something like:[['12', '30', '12', '23'. '3'], ['4','5','7','8','16']]
. The proper list method isguess.extend()
. Also, the values are strings, so even when they do compare, the comparison will never return true.