Loading...
Loading...
Combine conditions with and, or, not
Sometimes one condition isn't enough. You need to check multiple things at once: "Is the user logged in AND an admin?" or "Is it the weekend OR a holiday?" Logical operators let you combine conditions into powerful expressions.
age = 25
has_id = True
if age >= 18 and has_id:
print("You can enter!")| Operator | What it does | True Example |
|---|---|---|
| `and` | Both sides must be True | `5 > 3 and 2 < 4` ā True |
| `or` | At least one side must be True | `5 > 3 or 2 > 4` ā True |
| `not` | Flips True to False, False to True | `not (5 > 3)` ā False |
age = 20
has_license = True
if age >= 16 and has_license:
print("You can drive!") # ā
Runs: both conditions True| Condition 1 | Condition 2 | Result |
|---|---|---|
| True | True | ā True |
| True | False | ā False |
| False | True | ā False |
| False | False | ā False |
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("Sleep in!") # ā
Runs: weekend is True| Condition 1 | Condition 2 | Result |
|---|---|---|
| True | True | ā True |
| True | False | ā True |
| False | True | ā True |
| False | False | ā False |
logged_in = False
if not logged_in:
print("Please log in.") # ā
Runs: not False = TrueReal-world decisions almost always combine conditions:
| ā Wrong | Why | ā Right |
|---|---|---|
| `if age >= 18 and <= 65` | Must repeat the variable on both sides | `if age >= 18 and age <= 65:` |
| `if age == 18 or 19` | `19` is always Truthy ā bug! | `if age == 18 or age == 19:` |
| `if not age >= 18` | Works but reads awkwardly | `if age < 18:` (simpler!) |
| `if is_weekend == True` | Redundant | `if is_weekend:` |
Write a program that checks if someone can ride a roller coaster. They must:
Create the variables and write the if statement with and/not.
age = 14
height = 52
afraid = False
if age >= 12 and height >= 48 and not afraid:
print("Enjoy the ride!")