Python测试字符串是否为一组特定值之一 [英] Python testing whether a string is one of a certain set of values

查看:73
本文介绍了Python测试字符串是否为一组特定值之一的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm learning python on codecademy and my current task is this:


编写一个函数,shut_down,该函数需要一个参数(您可以随意使用
;在这种情况下,我们将s用于字符串)。当它获得,$ b时,shut_down
函数应返回正在关闭... $ b或作为参数,当时,关闭中止!

Write a function, shut_down, that takes one parameter (you can use anything you like; in this case, we'd use s for string). The shut_down function should return "Shutting down..." when it gets "Yes", "yes", or "YES" as an argument, and "Shutdown aborted!" when it gets "No", "no", or "NO".

如果除这些输入以外得到其他任何内容,该函数应将
return 对不起,我不明白您的意思。

If it gets anything other than those inputs, the function should return "Sorry, I didn't understand you."

对我来说似乎很容易我仍然做不到。

Seemed easy to me but somehow I still can't do it.

我编写的代码用来测试该功能:

My code I made to test the function:

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"

对于否和是,它都可以正常工作,但是如果我在任何是之前加上一个空格,即使我只是键入 a,它也会显示 Shutdown aborted!。

It works fine for the no's and yes', but somehow if I put a space before any yes or even if I just type in "a" it prints "Shutdown aborted!" although it should print "Sorry, I didn't understand you".

我在做什么错了?

推荐答案

您忘记在第一个 elif中写 s == no

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

执行此操作:

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

这是因为:

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

相同,因为这是公认的答案,因此我将详细介绍标准做法:比较字符串而不考虑大小写的惯例(equalsIgnoreCase)是使用 .lower() 像这样

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

这篇关于Python测试字符串是否为一组特定值之一的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆