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.

25 min 3 practice tasks
Python Tutorial for Beginners 6: Conditionals and Booleans - If, Else, and Elif Statements by Corey Schafer on YouTube

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:

  1. Each condition line ends with a colon :.
  2. The block underneath is indented (4 spaces is the convention). Indentation is how Python knows which lines belong to the branch.
  3. 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.5 first, 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.3 is actually False (the sum is 0.30000000000000004). When comparing calculated decimals, round first: round(0.1 + 0.2, 2) == 0.3 is True.

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.

1

Label a campaign's performance

The marketing team labels campaigns by click-through rate (in percent):

CTRtier
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?
  1. Check the highest threshold first: if ctr >= 3: then elif ctr >= 1.5:.
  2. Python runs only the first branch whose condition is True.
  3. Remember the colon at the end of each if/elif/else line and indent the body.
Python 3
ctr = 2.4

tier = "unknown"
# write your if / elif / else here

print(tier)
Files in the working directory
campaigns.csv (40 rows)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
2

Should we pause this campaign?

A 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 budget
  • profitable: revenue is greater than spend
  • should_pause: the campaign is active and over budget and not profitable
Need a hint?
  1. A comparison like spend > daily_budget already evaluates to True or False.
  2. Use == (two equals signs) to compare status with "active".
  3. Combine conditions with and and flip one with not.
Python 3
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)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country
3

Bucket an order for the finance report

Finance 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?
  1. Put the status check in the first if, so refunded orders never reach the amount checks.
  2. status.lower() != "completed" is True for "Refunded".
Python 3
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)
id, advertiser_id, name, channel, objective, start_date, end_date, daily_budget, status
daily_stats.csv (1,561 rows)
campaign_id, date, impressions, clicks, spend, conversions, revenue
customers.csv (300 rows)
id, first_name, last_name, email, country, segment, age_group, signup_date
orders.csv (900 rows)
id, customer_id, campaign_id, order_date, amount, status
advertisers.csv (12 rows)
id, name, industry, country