One condition is fine. But what if you need to check multiple conditions at once?
Imagine: you can ride the roller coaster only if age >= 10 AND height >= 140
Or: it’s a day off if Saturday OR Sunday
Logical operators let you combine conditions!
๐ค The AND operator โ both must be true
and = “AND” = all conditions must be True
Syntax:
if condition1 and condition2:
code runs only if BOTH are True
Example:
age = 17
has_license = True
if age >= 16 and has_license:
print("You can ride a scooter! ๐ต")
else:
print("Not yet")
What happens:
- age >= 16 โ 17 >= 16 โ True โ
- has_license โ True โ
- True and True โ True โ code runs!
Change age = 15:
- 15 >= 16 โ False โ
- True and False โ False โ code does NOT run
Real-world example โ movie access:
age = int(input("Age: "))
has_ticket = input("Do you have a ticket? (yes/no): ") == "yes"
if age >= 16 and has_ticket:
print("๐ฌ Enjoy the movie!")
else:
if age < 16:
print("โ Film is rated 16+")
elif not has_ticket:
print("โ You need a ticket")
More than two conditions:
age = 18
has_license = True
has_car = True
if age >= 18 and has_license and has_car:
print("๐ You're good to go!")
else:
print("โ Conditions not met")
All three must be True!
๐ซ The OR operator โ at least one must be true
or = “OR” = one True is enough
Syntax:
if condition1 or condition2:
code runs if AT LEAST ONE is True
Example:
day = input("What day is it? ")
if day == "Saturday" or day == "Sunday":
print("๐ Weekend!")
else:
print("๐ Weekday")
What happens:
- “Saturday” โ first is True โ result is True
- “Sunday” โ second is True โ result is True
- “Monday” โ both False โ result is False
Access control:
role = "admin"
if role == "admin" or role == "moderator":
print("โ
Admin panel access granted")
else:
print("โ Access denied")
Multiple or clauses:
grade = input("Grade: ")
if grade == "A" or grade == "B" or grade == "C":
print("โ
Passed!")
else:
print("โ Not passed")
Any grade of A, B, or C โ passed
๐ The NOT operator โ negation (inversion)
not = “NOT” = flips True to False and vice versa
Syntax:
if not condition:
code runs if the condition is False
Example:
is_raining = False
if not is_raining:
print("โ๏ธ Go for a walk!")
else:
print("โ Stay inside")
What happens:
- is_raining โ False
- not False โ True
- Code runs!
With variables:
is_logged_in = False
if not is_logged_in:
print("โ Please log in")
else:
print("โ
Welcome!")
NOT with comparison operators:
age = 15
if not age >= 18: # Same as: age < 18
print("You are under 18")
Though it’s cleaner to just write:
if age < 18:
print("You are under 18")
๐ Truth tables
AND โ all must be True:
True and True = True # Only this case yields True!
True and False = False
False and True = False
False and False = False
Rule of thumb: Any single False โ result is False
OR โ at least one True:
True or True = True
True or False = True # Any True โ result is True
False or True = True
False or False = False # Only both False โ result is False
Rule of thumb: Any single True โ result is True
NOT โ flips the value:
not True = False
not False = True
๐ฏ Combining operators
You can mix and, or, and not!
Example โ amusement park entry:
age = int(input("Age: "))
height = int(input("Height (cm): "))
# Entry allowed if:
# (age >= 10 AND height >= 140) OR age >= 16
if (age >= 10 and height >= 140) or age >= 16:
print("๐ข Welcome aboard!")
else:
print("โ Sorry, entry not allowed")
Let’s trace some cases:
1. Age 12, height 145: (12โฅ10 and 145โฅ140) โ True โ allowed โ
2. Age 9, height 145: (9โฅ10 and 145โฅ140) โ False, 9โฅ16 โ False โ not allowed โ
3. Age 17, height 130: (17โฅ10 and 130โฅ140) โ False, but 17โฅ16 โ True โ allowed! โ
Complex example โ VIP access:
age = 20
is_member = True
has_discount = False
# VIP if:
# (age >= 18 AND member) OR (NOT has_discount AND age >= 21)
if (age >= 18 and is_member) or (not has_discount and age >= 21):
print("โญ VIP access!")
else:
print("๐ซ Standard access")
Use parentheses for clarity!
๐ Operator precedence
When multiple operators are used together:
notfirst- Then
and - Then
or
Example:
x = True
y = False
z = True
result = not x and y or z
# Evaluated as:
# 1. not x โ not True โ False
# 2. False and y โ False and False โ False
# 3. False or z โ False or True โ True
# Result: True
Tip: Use parentheses to make the intent clear!
result = ((not x) and y) or z # Much clearer!
๐ก Real-world examples
1. Password validation:
password = input("Password: ")
length_ok = len(password) >= 8
has_digit = any(char.isdigit() for char in password)
if length_ok and has_digit:
print("โ
Strong password")
else:
if not length_ok:
print("โ Password too short (need >= 8 characters)")
if not has_digit:
print("โ Password must contain a digit")
2. Season detection:
month = int(input("Month (1-12): "))
if month == 12 or month == 1 or month == 2:
season = "Winter โ๏ธ"
elif month >= 3 and month <= 5:
season = "Spring ๐ธ"
elif month >= 6 and month <= 8:
season = "Summer โ๏ธ"
elif month >= 9 and month <= 11:
season = "Autumn ๐"
else:
season = "Invalid month"
print(season)
3. Basic email validation:
email = input("Email: ")
has_at = "@" in email
has_dot = "." in email
not_empty = len(email) > 0
if has_at and has_dot and not_empty:
print("โ
Email looks valid")
else:
print("โ Invalid email")
4. Game โ can the player attack?
health = 80
mana = 30
has_weapon = True
# Attack is possible if:
# health > 20 AND (mana >= 10 OR has_weapon)
if health > 20 and (mana >= 10 or has_weapon):
print("โ๏ธ Attack!")
else:
print("๐ก๏ธ Defend...")
โ ๏ธ Common mistakes
1. Forgetting to repeat the variable:
# โ Wrong:
if age >= 10 and >= 18:
print("OK")
# โ
Correct:
if age >= 10 and age <= 18:
print("OK")
# โ
Even better (Python idiom):
if 10 <= age <= 18:
print("OK")
2. Using = instead of ==:
# โ Assignment!
if age = 18 and has_ticket:
print("OK")
# โ
Comparison:
if age == 18 and has_ticket:
print("OK")
3. Confusing and vs or:
# Task: allow entry if EITHER age >= 18 OR has_parents
# โ Wrong (requires BOTH):
if age >= 18 and has_parents:
print("OK")
# โ
Correct (either one is enough):
if age >= 18 or has_parents:
print("OK")
4. Forgetting the keyword:
# โ Missing 'and':
if age >= 10 height >= 140:
print("OK")
# โ
Correct:
if age >= 10 and height >= 140:
print("OK")
๐ฎ Practice exercises
Easy level:
1. Range check
Is the number between 10 and 20 (inclusive)?
2. Day off
Is the day “Saturday” or “Sunday”?
3. NOT even
Is the number NOT even? (use not)
Medium level:
4. Exam eligibility
Eligible if: (attendance > 80% AND all homework submitted) OR has an individual plan
5. Discount
20% off if: (purchase >= 5000 AND has loyalty card) OR purchase >= 10000
6. Allowed to drive
Allowed if: age >= 18 AND has license AND NOT license revoked
Hard level:
7. Course access
Access if: (student AND paid) OR (teacher) OR (admin AND NOT blocked)
8. Triangle type
Given three side lengths, determine: equilateral / isosceles / scalene
๐ Summary
You’ve learned to:
โ
Use and to require ALL conditions
โ
Use or when ONE condition is enough
โ
Use not to invert a condition
โ
Combine operators
โ
Understand operator precedence
โ
Avoid common mistakes
With logical operators, your programs become much smarter! ๐ง
Practice in CodeHS! Build programs with different combinations of conditions. Experiment! ๐ช
๐ฌ Comments (0)
No comments yet
Be the first to share your opinion about this article!