我刚刚开始关注 python,我认为做一个小测验会很有趣。我遇到的问题是,当您考虑大写字母和常见的拼写错误时,会有很多可能的答案。我想考虑这些,但没有一堆“elif”函数。有没有办法将所有可能的答案都写在一行中?类似于 || 的东西在 C. 代码示例:
y = input("Where was the 2004 Olympics held? ")
if y == "Athens":
print ("Correct!")
score = score + 1
但允许 'athens' 或 'Greece' 作为答案
请您参考如下方法:
你想要的是:
answer = input("Where was the 2004 Olympics held? ")
if answer.lower() in ("athens", "greece"):
print ("Correct!")
score = score+1
我也在降低答案,所以大小写无关紧要!
注意:要构建测验,我会这样做:
qas = {
'Where was the 2004 Olympics held?': ['athens', 'greece'],
'What is the answer of the question about life, the universe and everything?': ['42', 'forty-two']
…
}
for q, a in qas:
ans = input(q)
if ans.lower() in a:
print("Correct!")
score += 1
