这是我改进的代码
w, r = 0,0
with open("questions.txt", "r", newline="") as file:
mycsv = csv.reader(file)
for question in list(mycsv):
print(question[0], "\n", question[1], "\n", question[2], "\n", question[3])
answer1 = input("Answer 'a','b' or 'c': ")
if answer1.strip() == question[4].strip():
if answer1 != (question[4]):
print("---------------------------------------------------")
print("Correct!")
print("---------------------------------------------------")
w = w + 1
r = r + 1
elif answer1 == (question[4]):
print("---------------------------------------------------")
print("Incorrect!")
print("---------------------------------------------------")
w = w + 1
elif w == 3:
print("Game over")
print("You got",r,"right out of 3")
如果用户回答错误,代码将无法打印错误,它将转移到下一个问题。完成3个问题后,它会打印一个超出范围错误的列表索引。
答案 0 :(得分:1)
每次循环时都会打开同一个文件。而是要打开文件一,然后循环CSV中的行。 (完全删除while循环)
import csv
w = 0
r = 0
with open("questions.txt", "r", newline="") as file:
mycsv = csv.reader(file)
for question in list(mycsv):
if len(question) != 5:
continue
print(question[0], "\n", question[1], "\n", question[2], "\n", question[3])
answer1 = input("Answer 'a','b' or 'c': ")
if answer1.strip() == question[4].strip():
print("---------------------------------------------------")
print("Correct!")
print("---------------------------------------------------")
w = w + 1
r = r + 1
else:
print("---------------------------------------------------")
print("Incorrect!")
print("---------------------------------------------------")
w = w + 1
if w == 3:
print("Game over")
print("You got", r, "right out of 3")
示例输入文件:
Correct is a, a, b, c, a
Correct is b, a, b, c, b
Correct is c, a, b, c, c
示例输出:
Correct is a
a
b
c
Answer 'a','b' or 'c': a
---------------------------------------------------
Correct!
---------------------------------------------------
Correct is b
a
b
c
Answer 'a','b' or 'c': b
---------------------------------------------------
Correct!
---------------------------------------------------
Correct is c
a
b
c
Answer 'a','b' or 'c': a
---------------------------------------------------
Incorrect!
---------------------------------------------------
Game over
You got 2 right out of 3
答案 1 :(得分:0)
您应该删除while
循环。我建议你使用一个函数检查每个答案:
with open('file.txt') as file:
content = file.readlines()
for line in content:
check_quiz() #function to ask the question and check the answer
由于您使用的是Python3,请使用\n
,如下所示:
print("----\n"+ "Incorrect!\n"+ "---")
更具表现力的变量名称也会有所帮助。在您的代码中还有其他一些可以改进的东西,请查看Stackoverflow的Code Review或教程。