Python If with AND Operator - Examples
Python If 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, providing a cleaner and more readable approach.
Examples
In the following examples, we will see how we can use Python AND logical operator to form a compound logical expression within conditional statements.
1. Python If with AND Operator
In this example, we will learn how to use the AND logical operator in a Python If statement to join two boolean conditions into one compound expression.
We will demonstrate the advantage of the AND operator by first writing a nested if and then simplifying it into a single if statement, achieving the same functionality with fewer lines of code.
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.')
In the above example, we check whether a equals 5 and whether b is greater than 0. Using the AND operator allows us to combine both conditions into a single statement, reducing the need for a nested if.
Output
a is 5 and b is greater than zero.
a is 5 and b is greater than zero.
2. Python If-Else with AND Operator
In this example, we will use the AND operator to combine two basic conditional expressions in a 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.')
Explanation:
- If a is equal to 5 and b is greater than 0, the message is printed. Otherwise, the else block is executed.
Output
a is not 5 or 2 is not greater than zero.
3. Python elif with AND Operator
In this example, we use the AND operator to combine two basic conditional expressions in a 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)')
Explanation:
- The first condition checks if a is less than 0. If a is not, it proceeds to the second condition, where we check if a is between 0 and 8 (exclusive). If that’s false, the third condition checks if a is between 7 and 15.
Output
a is in (7,15)
Summary
In this tutorial, we learned how to use the Python AND logical operator in Python conditional statements such as if
, if-else
, and elif
statements. By using the AND operator, we were able to combine multiple conditions into a single expression, simplifying our code and making it more efficient.