Explicitly evaluate both conditions when using Boolean and

I am not familiar with Python. From Java, I know that in conditional expressions, if we want both operands to be &&evaluated, we use instead &. For instance:

if ( x == 2 & y++ == 3)
    // do this

But I am working in python 2.7 and I want to perform an operation, for example:

if x == 2 and myList.pop() == 3:
    # do this

But both operands must be executed and.

In Python, the first comparison will be performed, and if it was false, the second comparison will be skipped. But I want both of them to be executed, even if the first comparison returned False. Is there any solution for this in Python?

+4
source share
3 answers

, and:

# explicitly execute the conditions first, compare the outcomes later
test1, test2 = x == 2, myList.pop() == 3
if test1 and test2:

, myList.pop():

# explicitly pop a value from myList, regardless of what x == 2 returns
myList_value = myList.pop()
if x == 2 and myList_value == 3:

, :

if myList.pop() == 3 and x == 2:

, list.pop() .

& Python , Java:

>>> from itertools import product
>>> for a, b in product([False, True], repeat=2):
...     print('{a!r:5} and {b!r:5}: {o1!r:5}    {a!r:5} & {b!r:5}: {o2!r:5}'.format(a=a, b=b, o1=a and b, o2=a & b))
... 
False and False: False    False & False: False
False and True : False    False & True : False
True  and False: False    True  & False: False
True  and True : True     True  & True : True 

, , :

>>> def foo():
...     print 'called!'
...     return False
... 
>>> def bar():
...     print 'also called!'
...     return False
... 
>>> foo() and bar()
called!
False
>>> foo() & bar()
called!
also called!
False

, . , .

+3

& python. __and__,

.

assert 3 & 6 == 2
assert True & 3 == 1

x = 0
y = [3]
assert not(x == 2 & y.pop() == 3)
assert y == []

, , . .

+1

python all() any(), .

&, all():

if (all([cond1, cond2])):
    ...

| any().

0

All Articles