Python测试字符串是否是某一组值中的一个
我正在codecademy上学习python,目前的任务是: 编写一个函数,关闭,它接受一个参数(您可以使用 您喜欢的任何内容;在本例中,我们将使用s表示字符串)。工厂关闭了 函数在得到“是”、“是”时应返回“正在关闭…”,“是”, 或者“是”作为参数,当它变为“否”时,“关机中止!”, “否”,或“否” 如果它得到的不是这些输入,函数应该 return“对不起,我听不懂您的意思。” 对我来说似乎很容易,但不知为什么我还是做不到 我为测试函数而编写的代码:Python测试字符串是否是某一组值中的一个,python,string,equality,Python,String,Equality,我正在codecademy上学习python,目前的任务是: 编写一个函数,关闭,它接受一个参数(您可以使用 您喜欢的任何内容;在本例中,我们将使用s表示字符串)。工厂关闭了 函数在得到“是”、“是”时应返回“正在关闭…”,“是”, 或者“是”作为参数,当它变为“否”时,“关机中止!”, “否”,或“否” 如果它得到的不是这些输入,函数应该 return“对不起,我听不懂您的意思。” 对我来说似乎很容易,但不知为什么我还是做不到 我为测试函数而编写的代码: def shut_down(s):
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”,它也会打印“关机中止!”,尽管它应该打印“对不起,我不明白你的意思”
我做错了什么?您忘记在第一次
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
Python将非空字符串计算为
True
,因此elif
条件总是计算为True
>>> bool('No')
True
>>> bool('NO')
True
使用True
值执行布尔或
操作将始终返回True
,因此它永远不会达到else
条件,并卡在elif
上
您需要使用来测试条件
elif choice=='no'或choice=='no'或choice=='no':
编辑-正如glglgl在评论中指出的,
==
比或
更难绑定,因此您的情况会被评估为(s=='No')或'No'或'No'
,而不是s==('No'或'No')
,在这种情况下,即使用户输入'NO'
而不是检查不同的大写组合,您也可以使用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."
这更干净,更容易调试。或者,您也可以使用upper
,并与中的“是”和中的“否”进行比较
如果由于匹配的情况(如nO
)而没有帮助,那么我将使用语句中的:
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中键入's=='。@Davlog但您是在Yes
行中这样做的@Davlog:如果一个答案解决了你的问题,你应该接受它。@Stephan另一个选项可以是if's in('Yes','Yes','Yes')
resp如果s在('No','No','No')
@Stephan是的,我没有忘记我也会这样做,但是作业很具体。@MatLecu阅读了为什么这样做。@MatLecu你可能有一点,所以在
中添加了一个替代方法。对不起,我的措辞不好:我知道为什么这样做,但是作业似乎说它不应该使用nO。编辑仍然比一堆or更好。也许值得注意的是,==
绑定更难,因此它的计算结果是(s==“nO”)或(“nO”)或(“nO”)
,而不是s==“nO”或“nO”)
。后者可以归结为答案中添加的s==“No”
@glglglgl:。谢谢。:)谢谢你们,几分钟后我会接受你们的回答。你帮了我很多,我想我永远不会再忘记“==”了,哈哈
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."