Decisions with if/else
Why this matters
Programs earn their keep by reacting to data. Send a lead to sales or to a slower email series. Flag a campaign that's overspending. Retry an API call that failed. Decide whether a model's answer passed a check. Every test you'll run on an AI system later comes down to conditions like the ones in this lesson.
- Compare values with ==, !=, <, >, <= and >=
- Run different code depending on a condition with if, elif and else
- Combine conditions with and, or and not
- Avoid the classic mistakes: = vs ==, indentation, and comparing floats
Comparisons give True or False
A comparison asks a yes-or-no question, like a light switch that's either on or off. The answer is a boolean: True or False.
| Operator | Asks | Example | Result |
|---|---|---|---|
== | equal? | 3 == 3 | True |
!= | not equal? | "paused" != "active" | True |
< / > | less / greater than? | 0.02 > 0.05 | False |
<= / >= | less / greater than or equal? | 5000 >= 5000 | True |
Note the double equals. A single = stores a value. A double == compares two values.
spend = 1890 budget = 2000 print(spend > budget) print(spend <= budget) print("active" == "Active") # text comparisons are case-sensitive
if: run code only when something is true
spend = 2150 budget = 2000 if spend > budget: print("Over budget!") print("Overspend:", spend - budget) print("Check complete")
The pattern is: if, a condition, a colon, then the lines to run, indented by four spaces. Those indented lines are the block. Python runs the block only when the condition is True.
The print at the end isn't indented, so it isn't part of the block. It runs either way. Change spend to 1500 and run it again.
Indentation isn't decoration in Python. It's how Python knows which lines belong to the if.
else and elif
Think of a sorting machine at a post office. A letter goes down the first chute that fits, and never reaches the others.
else runs when the if condition is false. elif ("else if") adds more conditions in between. Python checks them top to bottom, and runs only the first block whose condition is true. Then it skips the rest.