Python - if语句无法正常工作

时间:2014-01-09 17:09:30

标签: 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("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周围(所以负面答案的代码高于正面的代码答案)它总会回复,好像我给出了否定的回应。

4 个答案:

答案 0 :(得分:6)

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

if yearlikedislike.lower() in ("yes","yep","yup"):

会做的伎俩

答案 1 :(得分:2)

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

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

if the variable "yearlikedislike" equals "yes" or the string literal "Yes" is True (or "truthy"), do something

您需要每次与yearlikedislike进行比较。

试试这样:

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

答案 2 :(得分:2)

if (yearlikedislike == "yes" or "Yes" or "YES" or "yep" or "yup" or "Yep" or "Yup"):

字符串评估为True。我知道你认为你说如果像年轻人一样等同于任何一件事,那就继续吧。但是,你实际上说的是:

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")

答案 3 :(得分:1)

这是因为条件被解释为:

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

尝试

if(yearlikedislike == "yes" or yearlikedislike == "Yes" or yearlikedislike == "YES"#...

或更简洁的方式:

if(yearlikedislike in ("yes", "Yes", "YES", #...

更简洁的方式:

if(yearlikedislike.lower() in ("yes", "yup", #...

转换为布尔值的字符串(此处为“是”)如果不为空则转换为True

>>> bool("")
False
>>> bool("0")
True
>>> bool("No")
True

每个部分之后或独立于之前的部分。

另外考虑使用else或elif而不是两个相关的if。并且在测试它们之前尝试降低角色,这样你就需要更少的测试。