Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中的条件_Python - Fatal编程技术网

Python中的条件

Python中的条件,python,Python,我很难理解这个逻辑: >>> text = 'ay_118724981.jpg' >>> 'jpg' in text True >>> 'png' in text False >>> if 'png' not in text or 'jpg' not in text or 'jpeg' not in text: ... print('True') ... else: ... print('False') ..

我很难理解这个逻辑:

>>> text = 'ay_118724981.jpg'
>>> 'jpg' in text
True
>>> 'png' in text
False
>>> if 'png' not in text or 'jpg' not in text or 'jpeg' not in text:
...     print('True')
... else:
...     print('False')
... 
True
>>> 
我很困惑,因为if语句应该导致False,因为“jpg”在文本中是。只有当它们都不在文本中时,它才会给我真正的。正确吗?

它解析为
('png'不在文本中)或('jpg'不在文本中)或('jpeg'不在文本中)

其中一个条件为true('png'不在
文本中),因此其计算结果为true。您可以使用

我感到困惑[因为]if语句应该导致False,因为文本中有“jpg”。只有当它们都不在文本中时,它才应该给我真实的答案。对吗

否,如果一个或两个操作数为
True
,则
运算符为
True
。因此,从那一刻起,
'jpg'
不在文本中,或者
'png'
不在文本中,或者
jpeg
不在文本中,测试就成功了

这里需要的是
操作符<仅当两个操作数(
x
y
)不在文本中时,code>x和y
才为真。因此,我们可以使用:

if 'png' not in text and 'jpg' not in text and 'jpeg' not in text:
    print('True')
else:
    print('False')

因此,只有当所有这些
部分
都不在
s
中时,条件才会成功。

在这种情况下,您应该使用
。这样,从其中一个条件为
False
的那一刻起,它就失败了。并非所有字符串都在文本中:True。尽量避免否定,并检查德摩根定律
'png'不在文本中
真的
,之后的所有内容甚至都不会被评估<如果
a
为真或b为真或两者都为真,则code>a或b
为真。将你的陈述转换成英语,问自己“为什么程序的结果与你的预期不同”,你就会得到答案。此时,我开始怀疑你是否理解“或”这个词在英语中的含义。我想我理解这样的简单逻辑,但显然我需要复习一下。真的很尴尬是的。。。你们都这么说。我想我把它弄颠倒了。
if all(part not in s for part in ['png', 'jpg', 'jpeg']):
    print('True')
else:
    print('False')