Python and Keyword

The "and" keyword in Python works as a logical operator. It returns True only if both the expression evaluates to be True. For example:

Python Code
a = 10
b = 20
c = 30

if a<b and b<c:
    print(a, "is smallest")
else:
    print(a, "is not smallest")
Output
10 is smallest

From above program, since the left expression, that is a<b or 10<20 evaluates to be True, and the right expression, that is b<c or 20<30 also evaluates to be True. Therefore the whole expression including the and keyword, that is:

a<b and b<c

evaluates to be True. So the if statement including the evaluated condition becomes:

if True:

That indicates the program flow, to goes inside the if block and evaluate the following statement:

print(a, "is smallest")

that prints 10 is smallest on output as shown in the snapshot.

Note - The and keyword can be used to separate any number of expression. If all expressions, separated by and keyword, evaluates to be True, then only the whole expression evaluates to be True. That is, if any expression evaluates to be False, then of course, the whole expression evaluates to be False.

Python and Keyword with More than Two Expressions

This program uses and keyword to separate more than two expressions:

a = 10
b = 20
c = 30
d = 40
e = 50

if a<b and a<c and a<d and a<e:
    print(a, "is smallest")
else:
    print(a, "is not smallest")

The output is:

10 is smallest

Here is another example of and keyword in Python:

print(True and True and True and True and True)
print(True and True and True and False and True)

The output is:

True
False

Python and Keyword Truth Table

The truth table of and keyword is:

A B A and B
True True True
True False False
False True False
False False False

Python Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!