Learn Without Walls
← Previous Lesson Lesson 3 of 4 Next Lesson →

Lesson 4.3: Logical Operators

What You'll Learn

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.

Logical operators combine Boolean values (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.")
You can ride the roller coaster!

The and Operator

and returns True only when both conditions are True. If either one is False, the whole expression is False.

ABA and B
TrueTrueTrue
TrueFalseFalse
FalseTrueFalse
FalseFalseFalse
# Both conditions must be True
username = "admin"
password = "secret123"

if username == "admin" and password == "secret123":
    print("Login successful!")
else:
    print("Invalid credentials.")
Login successful!

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.")
42 is in the valid range.

The or Operator

or returns True when at least one condition is True. It is only False when both conditions are False.

ABA or B
TrueTrueTrue
TrueFalseTrue
FalseTrueTrue
FalseFalseFalse
# 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.")
It's the weekend!

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.")
You qualify for a discount!

The not Operator

not reverses a Boolean value. True becomes False, and False becomes True.

Anot A
TrueFalse
FalseTrue
is_raining = False

if not is_raining:
    print("It's a nice day for a walk!")
else:
    print("Better bring an umbrella.")
It's a nice day for a walk!
# 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.")
Access denied. Admin only. 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
True False
Best Practice: Always use parentheses when combining 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.")
You can rent a car!

Short-Circuit Evaluation

Python is smart about evaluating logical expressions. It stops as soon as it knows the result:

# 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")
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:

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

← if, elif, else Lesson 3 of 4 Next: Nested Conditionals →