这行不通:

if cond1 && cond2:

当前回答

你使用和和或来执行逻辑操作,就像在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

希望这能有所帮助!

其他回答

两个评论:

在Python中使用and和or进行逻辑操作。 缩进使用4个空格,而不是2个。您以后会感谢自己,因为您的代码看起来和其他人的代码几乎一样。更多细节请参见PEP 8。

在条件句中使用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

一个&(不是两个&&)就足够了,或者就像上面的答案所说的,你可以用and。 我在熊猫身上也发现了这一点

cities['Is wide and has saint name'] = (cities['Population'] > 1000000) 
& cities['City name'].apply(lambda name: name.startswith('San'))

如果我们将“&”替换为“and”,它将不起作用。

对于这个任务,这可能不是最好的代码,但它是有效的

def front_back(a, b):

 if len(a) % 2 == 0 and len(b) % 2 == 0:
    print a[:(len(a)/2)] + b[:(len(b)/2)] + a[(len(a)/2):] + b[(len(b)/2):]

 elif len(a) % 2 == 1 and len(b) % 2 == 0:
    print a[:(len(a)/2)+1] + b[:(len(b)/2)] + a[(len(a)/2)+1:] + b[(len(b)/2):] 

 elif len(a) % 2 == 0 and len(b) % 2 == 1:
     print a[:(len(a)/2)] + b[:(len(b)/2)+1] + a[(len(a)/2):] + b[(len(b)/2)+1:] 

 else :
     print a[:(len(a)/2)+1] + b[:(len(b)/2)+1] + a[(len(a)/2)+1:] + b[(len(b)/2)+1:]

Python使用and和or条件句。

i.e.

if foo == 'abc' and bar == 'bac' or zoo == '123':
  # do something