【发布时间】:2021-02-04 13:12:28
【问题描述】:
首先,对于我的帖子中的愚蠢问题或任何错误,我深表歉意! (这是我的第一篇文章!)
其次,我试图在 Stack Overflow 和 RealPython 网站(逻辑表达式)上查找此问题的答案,但我似乎仍然无法理解为什么这段代码返回“True”最后一个(未注释的)函数调用?
我正在尝试回答电子书“使用 Python 进行计算和编程简介”中的以下问题 -
“编写一个函数 isIn,它接受两个字符串作为参数,如果其中一个字符串出现在另一个字符串中,则返回 True,否则返回 False。提示:您可能希望使用内置的 str 操作 in。”
如果有人能解释(用外行的话)为什么下面的代码将“True”返回到最后一个函数调用,我将非常感激 - 再次为这个愚蠢的问题道歉!
def isIn(string1, string2):
"""Input two strings
Returns 'True' if either strings are within each other
"""
if string1 in string2 or string2 not in string1:
return True
else:
return False
# isIn('hello', 'hello') # Prints True
# isIn('hello', 'hello world') # Prints True
isIn('hello world', 'world hello') # Prints True
【问题讨论】:
-
它返回
True,因为string2不是in string1。你的意思是string1 in string2 or string2 in string1,没有not? -
感谢您的回复。我想包括“不在”表达,以尝试回答电子书中的问题,但我认为我做的不正确 - 道歉!
标签: python logical-operators notin