Python testing whether a string is one of a certain set of values

a 夏天 提交于 2019-11-27 16:12:35

You forgot to write s == "no" in your first elif:

def shut_down(s):
    if s == "Yes" or s == "yes" or s == "YES":
        return "Shutting down..."
    elif s == "No" or "no" or "NO":             # you forgot the s== in this line
        return "Shutdown aborted!" 
    else:
        return "Sorry, I didn't understand you."

Do this:

def shut_down(s):
    if s == "Yes" or s == "yes" or s == "YES":
        return "Shutting down..."
    elif s == "No" or s == "no" or s == "NO":       # fixed it 
        return "Shutdown aborted!"
    else:
        return "Sorry, I didn't understand you."

This is because:

elif s == "No" or "no" or "NO":  #<---this
elif s == "No" or True or True:  #<---is the same as this

Since this is the accepted answer I'll elaborate to include standard practices: The convention for comparing strings regardless of capitalization (equalsIgnoreCase) is to use .lower() like this

elif s.lower() == "no":

Instead of checking for different combinations of capitalization you could uses the lower function to return a copy of s in lowercase and compare against that.

def shut_down(s):
    if s.lower() == "yes":
        return "Shutting down..."
    elif s.lower() == "no":       
        return "Shutdown aborted!"
    else:
        return "Sorry, I didn't understand you."

This is much cleaner and easier to debug. Alternatively you could use upper also and compare against "YES" and "NO".


If this doesn't help because of matching cases like nO then I'd go with the in statement:

def shut_down(s):
    if s in ("yes","Yes","YES"):
        return "Shutting down..."
    elif s in ("no","No","NO"):       
        return "Shutdown aborted!"
    else:
        return "Sorry, I didn't understand you."

Python evaluates non empty strings to be True, so your elif condition is always evaluated to True.

>>> bool('No')
True

>>> bool('NO')
True

Doing a boolean or with a True value would always return True, so it never reaches the else condition and gets stuck on the elif one.

You need to test the conditions using.

elif choice == 'no' or choice == 'NO' or choice == 'No':

EDIT - As glglgl pointed out in the comment, == binds harder than or, so your condition gets evaluated as (s == 'No') or 'no' or 'NO' and not s == ('No' or 'no' or 'NO'), in which case you would have gotten to the else part even for a user input of 'NO'.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!