Section 1 · Lesson 3
Booleans, comparisons and if/elif/else
Compare values, combine conditions with and/or/not, and make decisions with if/elif/else.
Analysis is full of decisions: is this campaign over budget? Is this order a refund? Should it count toward revenue? Python makes these decisions with booleans and if statements.
Booleans and comparisons
A boolean (bool) has only two values: True and False (capitalized). You usually get
them from a comparison:
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
equal to | "search" == "search" |
True |
!= |
not equal to | 3 != 4 |
True |
> / < |
greater / less than | 1180 > 1000 |
True |
>= / <= |
at least / at most | 1.5 >= 1.5 |
True |
in |
contained in | "US" in "US,CA" |
True |
Watch the difference: = assigns a value, == compares two values.
String comparisons are case-sensitive, so "Active" == "active" is False. Data entered by
people is messy, so normalize first: status.lower() == "active".
Combining conditions
| Keyword | True when | Example |
|---|---|---|
and |
both sides are True | spend > 0 and clicks > 0 |
or |
at least one side is True | channel == "search" or channel == "social" |
not |
flips True and False | not profitable |
Python also lets you chain comparisons the way you would write them on paper:
1.5 <= ctr < 3 means “at least 1.5 and under 3”.
if, elif, else
An if statement runs a block of code only when its condition is True. Add elif
(“else if”) for more cases and else as the catch-all:
ctr = 2.4
if ctr >= 3:
tier = "high"
elif ctr >= 1.5:
tier = "medium"
else:
tier = "low"
print(tier) # medium
Three rules to remember:
- Each condition line ends with a colon
:. - The block underneath is indented (4 spaces is the convention). Indentation is how Python knows which lines belong to the branch.
- Python checks the conditions top to bottom and runs only the first branch that is
True. That’s why the order matters: if you tested
ctr >= 1.5first, a CTR of 4 would be labeled “medium” and the “high” branch would never run.
Truthiness
if also accepts non-boolean values. Zero, empty strings and None count as False;
everything else counts as True:
coupon_code = ""
if coupon_code:
print("Apply discount")
else:
print("No coupon") # this runs: "" counts as False
Tip: Decimal numbers are stored in binary, so
0.1 + 0.2 == 0.3is actuallyFalse(the sum is 0.30000000000000004). When comparing calculated decimals, round first:round(0.1 + 0.2, 2) == 0.3isTrue.
Putting it together
A typical business rule mixes everything in this lesson:
spend, daily_budget, status = 1180.0, 1000, "Active"
if status.lower() == "active" and spend > daily_budget:
print(f"Over budget by ${spend - daily_budget:,.2f}")
Next section you’ll apply rules like this to whole lists of campaigns at once.
Practice
Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.
Label a campaign's performance
DoneThe marketing team labels campaigns by click-through rate (in percent):
| CTR | tier |
|---|---|
| 3 or more | "high" |
| at least 1.5 but under 3 | "medium" |
| under 1.5 | "low" |
Given ctr = 2.4, write an if / elif / else block that sets the variable tier to the right label. (Your code should still work if someone changes ctr.)
Need a hint?
- Check the highest threshold first:
if ctr >= 3:thenelif ctr >= 1.5:. - Python runs only the first branch whose condition is True.
- Remember the colon at the end of each
if/elif/elseline and indent the body.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
ctr = 2.4
tier = "unknown"
# write your if / elif / else here
print(tier)
Files in the working directory
campaigns.csv (40 rows)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)Should we pause this campaign?
DoneA campaign has these numbers for today:
spend = 1180.0
daily_budget = 1000
revenue = 950.0
status = "active"Create three booleans using comparisons (don't type True/False yourself):
over_budget: spend is greater than the daily budgetprofitable: revenue is greater than spendshould_pause: the campaign is active and over budget and not profitable
Need a hint?
- A comparison like
spend > daily_budgetalready evaluates to True or False. - Use
==(two equals signs) to comparestatuswith"active". - Combine conditions with
andand flip one withnot.
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
spend = 1180.0
daily_budget = 1000
revenue = 950.0
status = "active"
over_budget = None
profitable = None
should_pause = None
print(over_budget, profitable, should_pause)
Files in the working directory
campaigns.csv (40 rows)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)Bucket an order for the finance report
DoneFinance groups orders into buckets. Given amount = 249.99 and status = "Refunded" (with a capital R, as it came from a web form), set bucket:
"exclude"if the status, lowercased, is anything other than"completed"- otherwise
"large"if the amount is 200 or more,"medium"if it is 50 or more,
and "small" for anything below 50
Need a hint?
- Put the status check in the first
if, so refunded orders never reach the amount checks. status.lower() != "completed"is True for "Refunded".
Practice tasks, quizzes and the certificate are part of the course. The first lesson is free to try.
amount = 249.99
status = "Refunded"
bucket = "large"
# replace the line above with if / elif / else logic
print(bucket)
Files in the working directory
campaigns.csv (40 rows)daily_stats.csv (1,561 rows)customers.csv (300 rows)orders.csv (900 rows)advertisers.csv (12 rows)