gpt4 book ai didi

python - 我的 if 变量没有触发

转载 作者:行者123 更新时间:2023-12-01 02:29:39 26 4
gpt4 key购买 nike

我正在尝试使用 python 进行测验,它从文本文件中读取问题。我有一个名为 ans 的变量,它应该是它从文件中读取的答案,我打印了该变量,它说了它应该说的内容,但如果我实际输入它,它会说它是错误的。这是我的Python代码:

right = 0
wrong = 0
num = 0
quest = 0
history = open("history.txt", "r")
lines = history.readlines()
while quest != 3:
quest = quest+1
num = num+1
print("Question", quest)
question = lines[num]
print(question)
num = num + 1
ans = lines[num]
print(ans)
answer = input()
answer = answer.lower()
if answer == ans:
print("correct")
right = right+1
else:
print("Wrong")
wrong = wrong+0
print("done")

我的history.txt文件的格式如下

Blank Line Blank Line
What is the capital of England?
london
What is 1+1?
2

谢谢。

最佳答案

history.readlines() 返回的字符串末尾有换行符,但 input() 返回的字符串没有。使用 rstrip() 删除字符串中的所有尾随空格。

ans = lines[num].rstrip()

关于python - 我的 if 变量没有触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46983732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com