为什么这个简单的python程序不能按照我想要的方式工作?

时间:2018-03-04 05:29:28

标签: python python-3.x

以下代码段旨在允许用户输入问题的答案。他们被允许进入四个 答案:{是{1}}或y代表“是”,或Yn代表“否”。该程序应该打印出收到的答案,如果 条目有效,否则打印出错误消息。

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还是随机的。有人可以向我解释一下吗?

3 个答案:

答案 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"]:

如果answeryY

,则会返回True