Python if语句不能正常工作

2024-10-01 11:39:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始使用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调换过来(因此否定答案的代码在肯定答案的代码之上),它总是会像我给出了否定回答一样回答。在


Tags: or答案代码youinputiftimesleep
3条回答
if (yearlikedislike == "yes" or "Yes" or "YES" or "yep" or "yup" or "Yep" or "Yup"):

字符串的计算结果为True。我知道你认为你是在说,如果像这样的年份等于这些东西,那就继续吧。但是,你的意思是:

^{pr2}$

你想要的是:

if (yearlikedislike == "yes" or yearlikedislike == "Yes" or yearlikedislike == "YES")

或更好:

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

这是因为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
if yearlikedislike in ("yes", "Yes", "YES", "yep", "yup", "Yep", "Yup"):

或者

^{pr2}$

会成功的

相关问题 更多 >