Loading...
Loading...
Make decisions with if and else
Programs don't just run line by line ā they make decisions. if statements let your code check a condition and run different code depending on whether it's True or False. This is how programs "think."
age = 18
if age >= 18:
print("You can vote!")
else:
print("Too young to vote.")| Part | What it's called | What it does |
|---|---|---|
| `if` | **Keyword** | Starts the decision block |
| `age >= 18` | **Condition** | An expression that evaluates to True or False |
| `:` | **Colon** | Marks the end of the condition ā don't forget it! |
| `print(...)` | **Body** | Indented code that runs only if condition is True |
| `else:` | **Alternative** | Optional ā runs when condition is False |
temperature = 30
if temperature > 25:
print("It's hot outside!")
else:
print("It's cool outside.")Step by step:
If temperature were 20 instead, Python would check 20 > 25 ā False ā, skip the if block, and run the else block instead.
| Operator | Meaning | True Example |
|---|---|---|
| `==` | Equal to | `5 == 5` |
| `!=` | Not equal to | `5 != 3` |
| `<` | Less than | `3 < 5` |
| `>` | Greater than | `5 > 3` |
| `<=` | Less than or equal | `5 <= 5` |
| `>=` | Greater than or equal | `5 >= 3` |
Every interactive program needs decisions:
| ā Wrong | Why | ā Right |
|---|---|---|
| `if age = 18:` | `=` is assignment, not comparison | `if age == 18:` |
| `if age >= 18` (no colon) | Colon is required at end of condition | `if age >= 18:` |
| if age >= 18: with no indented body | Indentation defines the block | `if age >= 18:
print(...)` |
| `if (age >= 18)` | Extra parens work but aren't needed in Python | `if age >= 18:` |
|---|
Create a variable age = 16. Write an if/else statement that prints "Adult" if age is 18 or older, and "Minor" otherwise.
age = 16
if age >= 18:
print("Adult")
else:
print("Minor")