我的IF语句无法正常运行,该如何解决?

时间:2020-04-01 16:30:38

标签: python

我正在创建一个测验程序,该程序从.txt文件中提取问题和答案。问题和答案的格式为:

问题,答案

.txt文件中的

。程序随机选择一个,并以逗号分隔并询问问题。然后将用户答案与问题答案相匹配,并检查其是否正确,例如:

if userAnswer == question[1]:
    print('Correct!')
else:
    print('Incorrect, better luck next time!')

每次我运行该程序时,都不会出错,但是无论输入什么,程序都会告诉我我不正确。我问了几个朋友,但他们都和我一样困惑,我们都不知道问题出在哪里。 代码拆分问题和答案:

f = open('Music.txt', 'r')
question = random.choice(list(f))
question = question.split(',')
userAnswer = input(f'Who sang {question[0]}? ').lower()

我应该澄清,.txt文件中的问题都是歌曲,所有答案都是乐队/歌手。没有答案包含逗号。

2 个答案:

答案 0 :(得分:1)

我猜想由于您的问题和答案是用新行分隔的,因此从文件中读取的答案以'\ n'结尾。 为了删除它,请运行:answer = answer.rstrip(),然后将其与作为用户输入提供的答案进行比较。

答案 1 :(得分:1)

这是我调试此类问题的方法:

import random
f = open('Music.txt', 'r')
question = random.choice(list(f))
question = question.split(',')
userAnswer = input(f'Who sang {question[0]}? ').lower()

print("userAnswer: {}".format(userAnswer))
print("{}\n".format([ord(i) for i in userAnswer]))
print("question[1]: {}".format(question[1]))
print("{}\n".format([ord(i) for i in question[1]]))
if userAnswer == question[1]:
    print('Correct!')
else:
    print('Incorrect, better luck next time!')

输出为

python tmp.py
Who sang Sandstorm? darude
userAnswer: darude
[100, 97, 114, 117, 100, 101]

question[1]: darude

[100, 97, 114, 117, 100, 101, 10]

Incorrect, better luck next time!

因此,您发现问题中还有一个附加字符,userAnswer中没有这个字符。 chr(10)给了我们\n

要摆脱任何开头或结尾的空格,可以使用strip

如果未提供chars参数,则会从字符串中删除所有前导和尾随空格。

如果将比较行更改为if userAnswer == question[1].strip():,它将按预期工作。