Python provides the AND logical operator. The AND logical operator is also expressed as & in some notations. The AND logical operator is used to check two or more boolean values and return True if all of them are True. If one or more of them are False the AND operation returns False.
AND Logic Operations
Before starting to learn Python AND operator we should understand the AND operator usage. Below you can find some operations and their results. When there is a False boolean value the complete statement is evaluated as False because the AND operator requires all boolean values to be True in order to return as True.
True AND True //Result is True True AND False //Result is False False AND False //Result is False True AND True AND True //Result is True True AND True AND False //Result is False True AND False AND False //Result is False
Python AND Operator
Python provides the AND operator with the and statement. Between boolean values the and statement can be used. In the following examples we will use different boolean statements with the AND logic operation.
print(True and False) print(True and True) print(True and False and True) print(True and True and True) print(True and True and True and True)
Alternatively the AND operator can be used for comparison operators. The >, <, == operators are comparison operators. The result of a comparison is a boolean value like True or False.
print( (1<2) and (2>1) ) print( (1==2) and (2>1) ) print( (12>5) and (2>1) and 1==1 )
Use AND Operator with if Statement
One of the most popular use case for the AND operatror is the if-else statements. by using the AND operator different selections and condititions can be easily checked and the execution of the application can be branched.
if 2>1 and 3>2: print("2>1 and 3>2") a=1 b=2 c=3 if a<2 and c>b: print("a<2 and c>b")