What are the boolean operators in Python
Using boolean operators
The following table lists the boolean operator in Python.
Operator | Meaning |
---|---|
not X | If X is false then True; else, False |
X or Y | If X is false then Y; else, X |
X and Y | If X is false then X; else, Y |
x, y = 3.1415926536, -1024# w ww . j a v a 2 s .com
print x < 5.0
print not (x < 5.0)
print (x < 5.0) or (y > 2.718281828)
print (x < 5.0) and (y > 2.718281828)
print not (x is y)
The code above generates the following result.
Using boolean operator with if statement.
number = 3# w ww . ja v a2s . c o m
if number <= 10 and number >= 1:
print 'Great!'
else:
print 'Wrong!'
The code above generates the following result.
and/ or on normal value
print 'a' and 'b'
print '' and 'b'
print 'a' and 'b' and 'c'
print 'a' or 'b'
print '' or 'b'
print '' or [] or {}
# w ww .ja va 2 s . c o m
def sidefx():
print "in sidefx()"
return 1
print 'a' or sidefx()
The code above generates the following result.
Combine the Boolean results
print 2 < 4 and 2 == 4
print 2 > 4 or 2 < 4
print not 6.2 <= 6
print 3 < 4 < 5
The code above generates the following result.
Boolean operator shortcut
The boolean operators would only evaluate expression if they need to. For example, the expression x and y requires that both x and y to be true. If x is false we would know x and y would be false without evaluate y. This behaviour is called short circuit.