不应该存在的 python 测验中的错误



我一直在创建一个智力竞赛游戏,必须从文件中随机选择一行。在我的主代码中,它不起作用,所以我在一个单独的文件中重写了代码。

#Import relevant modules
import csv
import time
import random
#declare placeholder variables
a=0
b=0

#create a random line function
def randomLine(fname):
lines = open(fname).read().splitlines()
return random.choice(lines)
def runQuiz():
a=1
c=0
print ('Welcome to the Quiz!')
while b == 0:
chosenLine = randomLine('songlist.csv')
print(chosenLine)
while chosenLine[c] != ',':
c += 1
print (c)

#run the function
runQuiz()

这是代码,当我运行它时,它会给我预期的输出,然后这个错误

Traceback (most recent call last):
File "Z:/NEA2020/OneDrive_1_12-11-2020/2.py", line 29, in <module>
runQuiz()
File "Z:/NEA2020/OneDrive_1_12-11-2020/2.py", line 23, in runQuiz
while chosenLine[c] != ',':
IndexError: string index out of range

知道是什么原因吗?

while chosenLine[c] != ',':
c += 1

将继续递增c,直到在您的行中找到逗号为止。一个可能的问题是行中没有逗号,这会使它变得太高,走得太远。

然而,我不认为这是你的实际问题。在while b == 0:循环开始时,您没有将c设置回0;因此它进入循环的新迭代,同时仍然具有从上一个随机行获得的值。这可能会使它立即尝试访问一个对新的随机线来说太高的值,从而生成IndexError

此外,您可以更换

while chosenLine[c] != ',':
c += 1
print (c)

通过

print(chosenLine.index(','))

上面的答案是正确的。

你可以做一些类似的事情

while b == 0:
global b
chosenLine = randomLine('songlist.csv')
print(chosenLine)
while chosenLine[c] != ',':
c += 1
print (c)
# include only one line or both as your requirements
b = 1   # if you want only one line 
c = 0 # if you want multiple lines 

最新更新