Python If Statement with Logical AND Operator

Python If with AND

You can combine multiple conditions into a single expression in Python conditional statements like Python if, if-else and elif statements. This avoids writing multiple nested if statements unnecessarily.

In the following examples, we will see how we can use Python and logical operator to form a compound logical expression.

Example 1: Python If Statement with AND Operator

In the following example, we will learn how to use AND logical operator, in Python If statement, to join two boolean conditions to form a compound expression.

To demonstrate the advantage of and operator, we will first write a nested if, and then a simple if statement where in this simple if statement realizes the same functionality as that of nested if.

Python Program

a = 5
b = 2

#nested if
if a==5:
	if b>0:
		print('a is 5 and',b,'is greater than zero.')
		
#or you can combine the conditions as
if a==5 and b>0:
	print('a is 5 and',b,'is greater than zero.')
Run this program

Here, our use case is that, we have to print a message when a equals 5 and b is greater than 0. Without using and operator, we can only write a nested if statement, to program out functionality. When we used logical and operator, we could reduce the number of if statements to one.

Output

a is 5 and b is greater than zero.
a is 5 and b is greater than zero.

Example 2: Python If-Else Statement with AND Operator

In the following example, we will use and operator to combine two basic conditional expressions in boolean expression of Python If-Else statement.

Python Program

a = 3
b = 2

if a==5 and b>0:
	print('a is 5 and',b,'is greater than zero.')
else:
	print('a is not 5 or',b,'is not greater than zero.')
Run this program

Output

a is not 5 or 2 is not greater than zero.

Example 3: Python elif Statement with AND Operator

In the following example, we will use and operator to combine two basic conditional expressions in boolean expression of Python elif statement.

Python Program

a = 8

if a<0:
	print('a is less than zero.')
elif a>0 and a<8:
	print('a is in (0,8)')
elif a>7 and a<15:
	print('a is in (7,15)')
Run this program

Output

a is in (7,15)

Summary

In this tutorial of Python Examples, we learned how to use Python and logical operator with Python conditional statement: if, if-else and elif with well detailed examples.