这行不通:
if cond1 && cond2:
这行不通:
if cond1 && cond2:
当前回答
两个评论:
在Python中使用and和or进行逻辑操作。 缩进使用4个空格,而不是2个。您以后会感谢自己,因为您的代码看起来和其他人的代码几乎一样。更多细节请参见PEP 8。
其他回答
两个评论:
在Python中使用and和or进行逻辑操作。 缩进使用4个空格,而不是2个。您以后会感谢自己,因为您的代码看起来和其他人的代码几乎一样。更多细节请参见PEP 8。
Python使用and和or条件句。
i.e.
if foo == 'abc' and bar == 'bac' or zoo == '123':
# do something
在条件句中使用and。我经常在导入Jupyter Notebook时使用这个:
def find_local_py_scripts():
import os # does not cost if already imported
for entry in os.scandir('.'):
# find files ending with .py
if entry.is_file() and entry.name.endswith(".py") :
print("- ", entry.name)
find_local_py_scripts()
- googlenet_custom_layers.py
- GoogLeNet_Inception_v1.py
我在IF条件中得到一个错误。我做错了什么?
你得到SyntaxError的原因是Python中没有&&操作符。同样||和!不是有效的Python操作符。
你可能从其他语言中知道的一些操作符在Python中有不同的名称。 逻辑运算符&&和||实际上被称为and和or。 同样,逻辑否定运算符!不叫不叫。
你可以这样写:
if len(a) % 2 == 0 and len(b) % 2 == 0:
甚至:
if not (len(a) % 2 or len(b) % 2):
一些额外的信息(可能会派上用场):
我总结了运算符“等价物”如下表所示:
+------------------------------+---------------------+
| Operator (other languages) | Operator (Python) |
+==============================+=====================+
| && | and |
+------------------------------+---------------------+
| || | or |
+------------------------------+---------------------+
| ! | not |
+------------------------------+---------------------+
参见Python文档:6.11。布尔操作。
除了逻辑操作符,Python还有位/二进制操作符:
+--------------------+--------------------+
| Logical operator | Bitwise operator |
+====================+====================+
| and | & |
+--------------------+--------------------+
| or | | |
+--------------------+--------------------+
在Python中没有按位的否定(只有按位的逆运算符~ -但这并不等同于not)。
参见6.6。一元算术和位/二进制运算和6.7。二进制算术运算。
逻辑运算符(像许多其他语言一样)的优点是它们是短路的。 这意味着如果第一个操作数已经定义了结果,则根本不计算第二个操作符。
为了说明这一点,我使用了一个函数,它简单地获取一个值,打印它并再次返回它。这很容易看出到底是什么 由于打印语句而求值:
>>> def print_and_return(value):
... print(value)
... return value
>>> res = print_and_return(False) and print_and_return(True)
False
正如你所看到的,只执行了一个print语句,所以Python实际上甚至没有查看正确的操作数。
二元运算符不是这样的。它们总是同时对两个操作数求值:
>>> res = print_and_return(False) & print_and_return(True);
False
True
但如果第一个操作数不够,那么当然,第二个操作符将被求值:
>>> res = print_and_return(True) and print_and_return(False);
True
False
下面是另一个表格:
+-----------------+-------------------------+
| Expression | Right side evaluated? |
+=================+=========================+
| `True` and ... | Yes |
+-----------------+-------------------------+
| `False` and ... | No |
+-----------------+-------------------------+
| `True` or ... | No |
+-----------------+-------------------------+
| `False` or ... | Yes |
+-----------------+-------------------------+
True和False代表bool(左边)返回的值,它们不一定是True或False,它们只需要在调用bool时返回True或False即可(1)。
所以在Pseudo-Code(!)中,and和or函数是这样工作的:
def and(expr1, expr2):
left = evaluate(expr1)
if bool(left):
return evaluate(expr2)
else:
return left
def or(expr1, expr2):
left = evaluate(expr1)
if bool(left):
return left
else:
return evaluate(expr2)
注意,这是伪代码而不是Python代码。在Python中,不能创建名为and或or的函数,因为它们是关键字。 另外,永远不要使用"evaluate"或if bool(…)。
自定义自己类的行为
这个隐式的bool调用可以用来自定义你的类使用and, or和not的行为。
为了展示如何自定义,我使用了这个类,它再次打印一些东西来跟踪正在发生的事情:
class Test(object):
def __init__(self, value):
self.value = value
def __bool__(self):
print('__bool__ called on {!r}'.format(self))
return bool(self.value)
__nonzero__ = __bool__ # Python 2 compatibility
def __repr__(self):
return "{self.__class__.__name__}({self.value})".format(self=self)
那么让我们看看这个类与这些操作符结合会发生什么:
>>> if Test(True) and Test(False):
... pass
__bool__ called on Test(True)
__bool__ called on Test(False)
>>> if Test(False) or Test(False):
... pass
__bool__ called on Test(False)
__bool__ called on Test(False)
>>> if not Test(True):
... pass
__bool__ called on Test(True)
如果你没有__bool__方法,那么Python也会检查对象是否有__len__方法,以及它是否返回一个大于零的值。 如果您要创建一个序列容器,了解这一点可能会很有用。
参见4.1。真值检验。
NumPy数组和子类
可能有点超出了原始问题的范围,但如果您正在处理NumPy数组或子类(如Pandas Series或DataFrames),则隐式bool调用 将引发可怕的ValueError:
>>> import numpy as np
>>> arr = np.array([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> arr and arr
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> import pandas as pd
>>> s = pd.Series([1,2,3])
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> s and s
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
在这些情况下,你可以使用NumPy中的逻辑和函数,它执行一个元素和(或或):
>>> np.logical_and(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([False, False, True, False])
>>> np.logical_or(np.array([False,False,True,True]), np.array([True, False, True, False]))
array([ True, False, True, True])
如果你只是处理布尔数组,你也可以使用NumPy的二进制操作符,它们确实执行元素(但也有二进制)比较:
>>> np.array([False,False,True,True]) & np.array([True, False, True, False])
array([False, False, True, False])
>>> np.array([False,False,True,True]) | np.array([True, False, True, False])
array([ True, False, True, True])
(1)
对操作数的bool调用必须返回True或False,这并不完全正确。它只是第一个需要在__bool__方法中返回布尔值的操作数:
class Test(object):
def __init__(self, value):
self.value = value
def __bool__(self):
return self.value
__nonzero__ = __bool__ # Python 2 compatibility
def __repr__(self):
return "{self.__class__.__name__}({self.value})".format(self=self)
>>> x = Test(10) and Test(10)
TypeError: __bool__ should return bool, returned int
>>> x1 = Test(True) and Test(10)
>>> x2 = Test(False) and Test(10)
这是因为and实际上返回第一个操作数,如果第一个操作数求值为False,如果它求值为True,那么它返回第二个操作数:
>>> x1
Test(10)
>>> x2
Test(False)
类似for or,但正好相反:
>>> Test(True) or Test(10)
Test(True)
>>> Test(False) or Test(10)
Test(10)
然而,如果你在if语句中使用它们,则if也会隐式地对结果调用bool。所以这些细节可能与你无关。
你使用和和或来执行逻辑操作,就像在C, c++。就像字面上的and && and or is ||。
看看这个有趣的例子,
假设你想用Python构建逻辑门:
def AND(a,b):
return (a and b) #using and operator
def OR(a,b):
return (a or b) #using or operator
现在试着称呼他们:
print AND(False, False)
print OR(True, False)
这将输出:
False
True
希望这能有所帮助!