我想我的计划已经完成了,但是。。。它不起作用。我试图编写一个模拟彩票游戏的程序,但是当我试图将用户的猜测与彩票上的猜测数进行比较时,我得到一个错误,告诉我“列表索引超出范围”。我想这和我给“a”、“b”、“c”分配随机数字的代码部分有关,但我不确定。
以下是完整的代码:
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()
这里是我得到的错误:
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
正如错误所指出的,问题在于:
错误在于您的列表索引超出范围——也就是说,您试图引用一些根本不存在的索引。在不完全调试代码的情况下,我将检查根据输入添加猜测的行:
你给用户的猜测数量的大小是基于
所以如果他们想要的票少于5张,那么你的代码在这里
将抛出错误,因为
guess
列表中没有那么多元素。这是你的密码。我假设您使用python 3是基于您使用的
print()
和input()
:我想你的意思是把随机a,b,c等的滚动放在循环中:
否则,
a
将只生成一次,如果它已经在winning_numbers
中,就不会被添加。由于a
的生成在while
(在您的代码中)之外,如果a
已经在winning_numbers
中,那么太糟糕了,它将不会被滚动,并且您将少一个中奖号码。这可能是导致您在
if guess[i] == winning_numbers[i]
中出错的原因。(您的winning_numbers
并不总是长度为5)。相关问题 更多 >
编程相关推荐