Python-if语句工作不正常

Python-if语句工作不正常,python,if-statement,Python,If Statement,我刚刚开始使用python,但在我看来,它显然应该是可行的。这是我的第一个代码,我只是尝试与用户进行对话 year = input("What year are you in school? ") yearlikedislike = input("Do you like it at school? ") if (yearlikedislike == "yes" or "Yes" or "YES" or "yep" or "yup" or "Yep" or "Yup"): print("W

我刚刚开始使用python,但在我看来,它显然应该是可行的。这是我的第一个代码,我只是尝试与用户进行对话

year = input("What year are you in school? ")
yearlikedislike = input("Do you like it at school? ")
if (yearlikedislike == "yes" or "Yes" or "YES" or "yep" or "yup" or "Yep" or "Yup"):
    print("What's so good about year " + year, "? ")
    input("")     
    print("That's good!")
    time.sleep(1)
    endinput = input("I have to go now. See you later! ")
    exit()
if (yearlikedislike == "no" or "No" or "nope" or "Nope" or "NOPE"):
    print("What's so bad about year " + year, "?")
    input("")
    time.sleep(1)
    print("Well that's not very good at all")
    time.sleep(1)
    endinput = input("I have to go now. See you later! ")
    time.sleep(1)
    exit()
我的问题是,即使我的回答是否定的,它也会像我说的是肯定的那样回答,如果我把2换过来(所以否定答案的代码高于肯定答案的代码),它总是会像我给出否定的回答一样回答

if yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup"):


这是因为该条件被解释为:

if(yearlikedislike == "yes" or "Yes" == True or "YES" == True #...
试一试

或者更简洁的方式:

if(yearlikedislike in ("yes", "Yes", "YES", #...
if(yearlikedislike.lower() in ("yes", "yup", #...
更简洁的方式:

if(yearlikedislike in ("yes", "Yes", "YES", #...
if(yearlikedislike.lower() in ("yes", "yup", #...
转换为布尔值的字符串(此处为“是”)如果不是空的,则会转换为True

>>> bool("")
False
>>> bool("0")
True
>>> bool("No")
True
每一部分都在前一部分之后或独立于前一部分


也考虑使用For或ELIF,而不是两个相关IF。在测试它们之前,尽量降低字符数,这样您就不需要太多的测试。

这是因为Python正在评估
“Yes”
的“真实性”

您的第一条if语句的解释如下:

if yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup"):
    #do something
如果变量“yearlikedislike”等于“yes”或字符串文字“yes”为True(或“truthy”),请执行操作

每次都需要与
年进行比较,如类似

试着这样做:

if yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup"):
    #do something
字符串的计算结果为True。我知道你认为你是在说如果yearlikedislike等于这些东西中的任何一个,继续。然而,你实际上说的是:

if yearlikedislike equals "yes", or if "Yes" exists (which it does), or "YES" exists, etc:
您想要的是:

if (yearlikedislike == "yes" or yearlikedislike == "Yes" or yearlikedislike == "YES")
或者更好:

yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup")

您可能还想引入
str.lower
同意。是的,是的,被遗漏了,更不用说任何其他的组合了。我已经编辑了你的答案,包括str。lower thing这只是一个解决方案。您还应该解释为什么OP的尝试是为了学习而给出输出。