我是Python的新手,并且正在进行多项选择测验,该测验从文件中读取问题并保留分数然后写入文件。
在我将验证添加到用户给出的答案之前,一切都运行良好。现在,当我运行该程序时,它说我的答案是错误的!
我做了什么?
适用的版本1
def inputandoutput():
questions_file = open_file("questions.txt", "r")
title = next_line(questions_file)
welcome(title)
score = 0
# get first block
category, question, answers, correct, explanation = next_block(questions_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer
answer = input("What's your answer?: ")
# check answer
if answer == correct:
print("\nRight!", end=" ")
score += 1
else:
print("\nWrong.", end=" ")
print(explanation)
print("Score:", score, "\n\n")
# get next block
category, question, answers, correct, explanation = next_block(questions_file)
questions_file.close()
版本2说我现在有错误的答案
def inputandoutput():
questions_file = open_file("questions.txt", "r")
title = next_line(questions_file)
welcome(title)
score = 0
# get first block
category, question, answers, correct, explanation = next_block(questions_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer and validate
while True:
try:
answer = int(input("What's your answer?: "))
if answer in range (1,5):
break
except ValueError:
print ("That's not a number")
else:
print ("the number needs to be between 1 and 4, try again ")
# check answer
if answer == correct:
print("\nRight!", end=" ")
score += 1
else:
print("\nWrong.", end=" ")
print(explanation)
print("Score:", score, "\n\n")
# get next block
category, question, answers, correct, explanation = next_block(questions_file)
帮助?
答案 0 :(得分:4)
在原始版本中,answer
是一个字符串;在您的新版本中,它是int
。
如果您将try
正文更改为:
answer = input("What's your answer?: ")
if int(answer) in range (1,5):
然后你仍然可以抓住ValueError
但是留下answer
一个字符串。