Python测试字符串是否是某组值中的一个

Dav*_*log 5 python string equality

我在codecademy上学习python,我目前的任务是:

编写一个函数shut_down,它接受一个参数(你可以使用你喜欢的任何东西;在这种情况下,我们使用s作为字符串).当shut_down函数获得"是","是""是"作为参数时,应该返回"关闭...",并且"关闭已中止!" 当它变为"否", "否""否"时.

如果它得到的不是那些输入,该函数应该返回"抱歉,我不明白你."

看起来很容易,但不知怎的,我仍然无法做到这一点.

我用来测试函数的代码:

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

i = input("Do you want to shutdown?")
print(i) #was to test the input
print(shut_down(i)) #never returns "Sorry, I didn't understand you"
Run Code Online (Sandbox Code Playgroud)

它适用于no和yes',但不知何故,如果我在任何之前放置一个空格,或者即使我只输入"a",它也会打印出"Shutdown aborted!" 虽然它应该打印"对不起,我不明白你".

我究竟做错了什么?

Ste*_*han 11

你忘记写s == "no"第一篇了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."
Run Code Online (Sandbox Code Playgroud)

做这个:

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."
Run Code Online (Sandbox Code Playgroud)

这是因为:

elif s == "No" or "no" or "NO":  #<---this
elif s == "No" or True or True:  #<---is the same as this
Run Code Online (Sandbox Code Playgroud)

由于这是公认的答案,我会详细说明,包括标准的做法:对于比较不分大小写字符串的约定(equalsIgnoreCase)就是用.lower()这样的

elif s.lower() == "no":
Run Code Online (Sandbox Code Playgroud)

  • @Davlog但你在"是"行中这样做了吗?! (3认同)
  • @Stephan另一个选择可能是`if s in('Yes','yes','YES')`resp.`if s in('No','no','NO')`. (2认同)
  • @Stephan是的,我没有忘记 (2认同)

Chr*_*our 6

您可以使用该lower函数返回s小写的副本并与之进行比较,而不是检查大小写的不同组合.

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."
Run Code Online (Sandbox Code Playgroud)

这样更干净,更容易调试.或者你也可以使用upper并比较"YES""NO".


如果由于匹配案例而没有帮助,nO那么我会使用in声明:

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."
Run Code Online (Sandbox Code Playgroud)