Connecting Conditions With Logical Operators
In this lesson, you will learn how to combine multiple comparison expressions into a single, powerful decision using the logical operators and, or, and not.
Combining Logic
So far, you have used if statements to check a single condition, such as if age >= 18:. But what if you need to check two things at once? This is where logical operators come in.
and: ReturnsTrueonly if both sides are true. Use this when you have strict requirements.or: ReturnsTrueif at least one side is true. Use this when you have flexible options.not: Flips the result. If a condition isTrue,notmakes itFalse.
Putting It Into Practice
Imagine you are writing a program to decide if someone qualifies for a discount at a movie theater. They need to be either a senior citizen (65+) OR a student (under 18).
age = 20
is_student = True
# Using 'or' to check if either condition is met
if age >= 65 or is_student:
print("You qualify for the discount!")
else:
print("Standard ticket price applies.")
You can even combine these to build complex rules. For example, if you wanted to check if someone is a student but not older than 25:
age = 22
is_student = True
if is_student and not age > 25:
print("Student discount active.")
By connecting conditions, your programs move away from simple "yes/no" checks and start behaving more like intelligent decision-makers. You are no longer limited to checking one fact; you can now evaluate a complete set of circumstances to determine the best path for your code to take.
Key Takeaway: Logical operators allow you to merge multiple conditions into a single statement, giving you precise control over your program's flow based on complex criteria.