Making Decisions
Programs can make choices! Use if to run code only when something is true.
The if Statement
python
age = 15
if age >= 12:
print("You can ride the roller coaster!")
If the condition is true, the indented code runs. If not, it's skipped.
Comparison Operators
| Operator | Meaning |
|---|---|
== | Equal to |
!= | Not equal to |
< | Less than |
> | Greater than |
<= | Less than or equal |
>= | Greater than or equal |
if / else
Use else for when the condition is false:
python
age = 8
if age >= 12:
print("You can ride!")
else:
print("Too young!")
Output:
text
Too young!
if / elif / else
Use elif (short for "else if") to check multiple conditions:
python
score = 85
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("F")
Output:
text
B
Boolean Logic
Combine conditions with and, or, and not:
python
age = 10
has_ticket = True
if age >= 8 and has_ticket:
print("Enjoy the show!")
Indentation Matters!
The indented code belongs to the if. Wrong indentation causes errors:
python
# Correct
if age >= 12:
print("Welcome!")
# Wrong — will cause an error!
if age >= 12:
print("Welcome!")