2014-01-09 98 views
2

我刚刚开始使用python,并且陷入了一些在我看来应该工作的东西。这是我的第一个代码,我只是试图与用户进行对话。Python - if语句工作不正确

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左右(所以对于否定答案的代码是上面的代码为正面答案),它总是会回复,就好像我已经给出了否定的答复。

回答

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

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

会做的伎俩

+1

+1打我吧:) –

+2

您可能也想介绍'str。低' – iCodez

+0

同意。 YEP和YUP错过了,更不用说其他组合了。 – mhlester

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。在测试它们之前尽量降低字符,这样你就不需要测试了。

3

这是因为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
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")