Lesson 4.3: Logical Operators
What You'll Learn
- How to combine conditions using
and,or, andnot - Truth tables for each logical operator
- How short-circuit evaluation works
- Order of operations with logical operators
- Practical patterns for combining conditions
Why Logical Operators?
Sometimes a single comparison is not enough to make a decision. For example, to ride a roller coaster you might need to be tall enough AND old enough. Logical operators let you combine multiple conditions into one.
True/False)
to produce a new Boolean result. Python has three: and, or, and not.
age = 15 height = 140 # in cm # Must be at least 12 AND at least 120cm tall if age >= 12 and height >= 120: print("You can ride the roller coaster!") else: print("Sorry, you can't ride yet.")
The and Operator
and returns True only when both conditions are
True. If either one is False, the whole expression is False.
| A | B | A and B |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
# Both conditions must be True username = "admin" password = "secret123" if username == "admin" and password == "secret123": print("Login successful!") else: print("Invalid credentials.")
Real-World Example: Range Check
# Check if a number is between 1 and 100 (inclusive) number = 42 if number >= 1 and number <= 100: print(f"{number} is in the valid range.") else: print(f"{number} is out of range.")
The or Operator
or returns True when at least one condition is
True. It is only False when both conditions are False.
| A | B | A or B |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
# At least one condition must be True day = "Saturday" if day == "Saturday" or day == "Sunday": print("It's the weekend!") else: print("It's a weekday.")
Real-World Example: Discount Eligibility
age = 70 is_student = False is_veteran = True # Discount if any of these conditions are met if age >= 65 or is_student or is_veteran: print("You qualify for a discount!") else: print("Regular price applies.")
The not Operator
not reverses a Boolean value. True becomes False,
and False becomes True.
| A | not A |
|---|---|
| True | False |
| False | True |
is_raining = False if not is_raining: print("It's a nice day for a walk!") else: print("Better bring an umbrella.")
# not is useful for checking "is NOT something" user_role = "guest" if not user_role == "admin": print("Access denied. Admin only.") # Equivalent (and often preferred): if user_role != "admin": print("Access denied. Admin only.")
Combining Logical Operators
You can combine and, or, and not in the same expression.
Python follows this order of precedence: not first, then and,
then or. Use parentheses to make your intent clear.
# Without parentheses - and is evaluated before or print(True or True and False) # True or (True and False) = True or False = True # With parentheses - changes the order print((True or True) and False) # (True or True) and False = True and False = False
and and
or to make your intent crystal clear, even when you know the precedence rules.
Real-World Example: Complex Eligibility Check
age = 25 has_license = True has_insurance = True has_violations = False # Can rent a car: must be 21+, have license, have insurance, no violations if (age >= 21) and has_license and has_insurance and (not has_violations): print("You can rent a car!") else: print("Sorry, you cannot rent a car.")
Short-Circuit Evaluation
Python is smart about evaluating logical expressions. It stops as soon as it knows the result:
and: If the first condition isFalse, Python does not bother checking the second (the result must beFalse)or: If the first condition isTrue, Python does not check the second (the result must beTrue)
# Short-circuit with and x = 0 # Python checks x != 0 first. Since it's False, # it skips the division (which would cause an error!) if x != 0 and 10 / x > 2: print("Result is greater than 2") else: print("x is zero or result is not greater than 2")
This is a useful pattern! By checking x != 0 first, you prevent a
ZeroDivisionError from the 10 / x part.
Try It Yourself!
Write a program that checks if a year is a leap year. A year is a leap year if:
- It is divisible by 4, AND
- It is NOT divisible by 100, OR it IS divisible by 400
year = 2024 if (year % 4 == 0) and (year % 100 != 0 or year % 400 == 0): print(f"{year} is a leap year") else: print(f"{year} is not a leap year")
Test with: 2024 (leap), 1900 (not leap), 2000 (leap), 2023 (not leap).
Check Your Understanding
What does each expression evaluate to?
print(True and True) print(True and False) print(False or True) print(not True) print(not (5 > 3)) print(3 > 1 and 5 < 2)
True # True and True = True False # True and False = False True # False or True = True False # not True = False False # 5 > 3 is True, not True = False False # 3 > 1 is True, 5 < 2 is False, True and False = False
Key Takeaways
andrequires both conditions to beTrueorrequires at least one condition to beTruenotreverses a Boolean value- Precedence order:
not→and→or - Use parentheses to make complex expressions clear
- Short-circuit evaluation can prevent errors