以下代码段旨在允许用户输入问题的答案。他们被允许进入四个
答案:{是{1}}或y
代表“是”,或Y
或n
代表“否”。该程序应该打印出收到的答案,如果
条目有效,否则打印出错误消息。
N
我只是继续说我回答answer = input("What is your answer? ")
if answer == "y" or "Y":
print("You answered yes")
elif answer == "n" or "N":
print("You answered no")
else:
print("You didn’t enter an acceptable answer")
,无论我是yes
还是n
还是随机的。有人可以向我解释一下吗?
答案 0 :(得分:6)
or
的优先级不是您所期望的。而是尝试:
answer = input("What is your answer? ")
if answer in ("y", "Y"):
print("You answered yes")
elif answer in ("n", "N"):
print("You answered no")
else:
print("You didn’t enter an acceptable answer")
或者也许喜欢:
answer = input("What is your answer? ")
if answer.lower() == "y":
print("You answered yes")
elif answer.lower() == "n":
print("You answered no")
else:
print("You didn’t enter an acceptable answer")
答案 1 :(得分:4)
您的第一个条件将始终返回true,因为"Y"
始终是真实的。
尝试:if answer == "y" or answer == "Y":
对其他条件的修改也是如此。
答案 2 :(得分:0)
如果您想根据需要立即检查变量,请使用以下内容:
if answer in ["y","Y"]:
如果answer
为y
或Y