Creo que tengo mi programa completo, pero ... no funciona. Intento escribir un programa que simule un juego de lotería, pero cuando trato de verificar las conjeturas del usuario con respecto al número de conjeturas en el ticket, aparece un error que me dice que el "índice de la lista está fuera de rango". Creo que tiene algo que ver con la parte del código donde asignó los dígitos aleatorios a "a", "b", "c", etc. Pero no estoy seguro.Python: IndexError: lista de índice fuera de rango
Este es el código en su totalidad:
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()
Y aquí está el error que consigo:
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
leer el rastreo, en la mayoría de los casos puede ser útil. – monkut
¿cuánto duran los números ganadores? Creo que encontrarás que es <= 5. Su generador de números ganador es defectuoso. Debe colocar 'a = randint (1,30)' _inside_ en el ciclo while. De lo contrario, solo lo ejecuta una vez. –
también, no hay absolutamente ninguna razón para usar la línea 'del myList [:]' En la función 'getguess',' guess' se define dentro del alcance de la función. inicialice la suposición con 'guess = []'. –