![]() |
VOOZH | about |
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.
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.
if (cond1 AND/OR cond2) AND/OR (cond3 AND/OR cond4):
code1
else:
code2
Python provides two logical operators to combine conditions:
Let’s see examples to understand better.
Example 1: This program grants access only to kids aged between 8 and 12.
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.
YOU SAID NO
Explanation:
Example 3: This program checks which of the three numbers is the largest. If all numbers are equal, it prints that too.
9 is the largest
Explanation:
Example 4: This program checks if all three values are equal to 1.
working
Explanation: The condition uses and. Since all three variables are equal to 1, it prints "working".