In Python, we often need to make decisions based on more than one condition. For example, you can only vote if your age is at least 18 and you are a registered citizen. Python makes this possible using logical operators like and and or inside if statements.
Before checking multiple conditions, let’s first recall a simple if-else.
age = 18
if age >= 18:
print("You are an adult")
else:
print("You are a minor")
Output
You are an adult
Explanation: If the condition age >= 18 is true, "You are an adult" is printed. Otherwise, "You are a minor" is printed.
Multiple Conditions in if Statement
Syntax
if (cond1 AND/OR cond2) AND/OR (cond3 AND/OR cond4):
code1
else:
code2
Python provides two logical operators to combine conditions:
- and: All conditions must be true. If the first condition is false, Python does not check the next one (short-circuiting).
- or: At least one condition must be true. If the first condition is true, Python does not check the next one.
Let’s see examples to understand better.
Examples
Example 1: This program grants access only to kids aged between 8 and 12.
age = 18
if (age >= 8 and age <= 12):
print("YOU ARE ALLOWED. WELCOME!")
else:
print("SORRY! YOU ARE NOT ALLOWED. BYE!")
Output
SORRY! YOU ARE NOT ALLOWED. BYE!
Explanation: Condition (age >= 8 and age <= 12) checks if age is between 8 and 12. Since age = 18, condition is false, so the else part runs.
Example 2: This program checks whether a user agrees to the terms or not.
var = 'N'
if (var == 'Y' or var == 'y'):
print("YOU SAID YES")
elif (var == 'N' or var == 'n'):
print("YOU SAID NO")
else:
print("INVALID INPUT")
Output
YOU SAID NO
Explanation:
- If input is "Y" or "y", it prints "YES".
- If input is "N" or "n", it prints "NO".
- Otherwise, it shows "INVALID INPUT".
Example 3: This program checks which of the three numbers is the largest. If all numbers are equal, it prints that too.
a = 7
b = 9
c = 3
if a > b and a > c:
print(a, "is the largest")
elif b > a and b > c:
print(b, "is the largest")
elif c > a and c > b:
print(c, "is the largest")
else:
print("All numbers are equal or there is a tie")
Output
9 is the largest
Explanation:
- First if checks if a is greater than both b and c. If not, elif checks if b is greater than both others.
- If not, next elif checks if c is greater than both others.
- If none of the above are true, it means either all numbers are equal or two numbers are tied, so the else block runs.
Example 4: This program checks if all three values are equal to 1.
a = 1
b = 1
c = 1
if (a == 1 and b == 1 and c == 1):
print("working")
else:
print("stopped")
Output
working
Explanation: The condition uses and. Since all three variables are equal to 1, it prints "working".