Section 2 · Lesson 3

Functions and comprehensions

Package logic in reusable functions, and build lists and dictionaries in one readable line.

30 min 3 practice tasks
Python Tutorial for Beginners 8: Functions by Corey Schafer on YouTube

As your scripts grow, you’ll notice the same few lines showing up again and again: compute a CTR here, a CPC there. Functions let you write that logic once, give it a name, and reuse it. Comprehensions let you build a whole list or dictionary in a single line.

Defining a function

def cpc(spend, clicks):
    """Cost per click, rounded to cents."""
    return round(spend / clicks, 2)

cpc(1288.40, 742)    # 1.74
cpc(980.5, 610)      # 1.61
  • def starts the definition, followed by the name and the parameters in parentheses.
  • The indented body runs each time you call the function.
  • return sends a value back to whoever called it. The optional text in triple quotes (a docstring) describes what the function does.

return vs print

This is the most common beginner mix-up. print only shows a value on screen; return hands it back so you can store it or use it in further calculations.

def show_cpc(spend, clicks):
    print(round(spend / clicks, 2))

x = show_cpc(100, 40)   # displays 2.5
print(x)                # None: the function returned nothing

If a function has no return, it returns None.

Guarding against bad input

Real data has zeros and gaps. Check for them first and return early:

def cpa(spend, conversions):
    if conversions == 0:
        return None          # no conversions: CPA is undefined
    return round(spend / conversions, 2)

Default values

Parameters can have defaults, which callers may override:

def with_fee(amount, fee_rate=0.15):
    return round(amount * (1 + fee_rate), 2)

with_fee(1000)          # 1150.0
with_fee(1000, 0.10)    # 1100.0

List comprehensions

In the previous lesson you built lists with a loop and .append(). A comprehension does the same thing in one line:

spend = [682.23, 613.15, 621.25, 593.23]

# transform: loop version
with_fee = []
for s in spend:
    with_fee.append(round(s * 1.15, 2))

# transform: comprehension version
with_fee = [round(s * 1.15, 2) for s in spend]

# filter: keep only some items
big_days = [s for s in spend if s > 600]     # [682.23, 613.15, 621.25]

Read it as “give me expression for each item in list (if condition)”.

Conditional expressions

Sometimes you want one value or another in a single line:

spend, budget = 1180.0, 1000
label = "over" if spend > budget else "ok"     # 'over'

This fits nicely inside comprehensions: ["big" if a >= 100 else "small" for a in amounts].

Dictionary comprehensions

Same idea, with key: value in curly braces:

budgets = {"search": 450, "social": 400, "video": 800}
weekly = {channel: b * 7 for channel, b in budgets.items()}
# {'search': 3150, 'social': 2800, 'video': 5600}
You want Write
a new list from a list [f(x) for x in items]
a filtered list [x for x in items if cond]
a dict from a dict {k: f(v) for k, v in d.items()}

Tip: Comprehensions are for building collections. If the logic needs several steps or nested ifs, a regular loop (or a helper function used inside the comprehension) is easier for your teammates to read.

Practice

Write your answer, press Run to see results and Check answer to grade it. Shortcuts: Ctrl/⌘ + Enter run, Shift + Enter check.

1

A safe CTR function

Write a function ctr(clicks, impressions) that returns the click-through rate as a percentage (clicks ÷ impressions × 100), rounded to 2 decimals.

Some new campaigns have 0 impressions, and dividing by zero crashes Python. If impressions is 0, the function should return 0.0 instead.

Examples: ctr(742, 51200) returns 1.45; ctr(5, 0) returns 0.0.

Need a hint?
  1. Start the function with if impressions == 0: and return 0.0 inside it.
  2. return sends the value back to the caller; print only displays it.
  3. The last line can be return round(clicks / impressions * 100, 2).
Python 3
def ctr(clicks, impressions):
    pass  # replace with your code


print(ctr(742, 51200))
print(ctr(5, 0))
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

Transform and filter with comprehensions

order_amounts = [38.92, 39.94, 15.84, 249.5, 87.25, 120.0, 64.1, 11.9] (US dollars).

Using list comprehensions, create:

  • amounts_eur: every amount converted to euros (× 0.92), rounded to 2 decimals, same order
  • big_orders: only the original dollar amounts that are 100 or more, same order
Need a hint?
  1. Transform: [expression for a in order_amounts]; put round(a * 0.92, 2) as the expression.
  2. Filter: add an if at the end: [a for a in order_amounts if a >= 100].
Python 3
order_amounts = [38.92, 39.94, 15.84, 249.5, 87.25, 120.0, 64.1, 11.9]

amounts_eur = [a for a in order_amounts]
big_orders = [a for a in order_amounts]

print(amounts_eur)
print(big_orders)
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

CPC for every campaign

Spend and clicks per campaign are stored in two dictionaries with the same keys:

spend = {"Search": 1250.0, "Social": 980.5, "Video": 2100.0, "Display": 0.0}
clicks = {"Search": 820, "Social": 610, "Video": 1750, "Display": 0}

1. Write a function cpc(spend, clicks) that returns spend ÷ clicks rounded to 2 decimals, or None when clicks is 0. 2. Use a dictionary comprehension with your function to build cpc_by_campaign, mapping each campaign name to its CPC. Expected: {"Search": 1.52, "Social": 1.61, "Video": 1.2, "Display": None}

Need a hint?
  1. In cpc, check if clicks == 0: first and return None.
  2. A dict comprehension looks like {key: value for name in spend}.
  3. For each name, the value is cpc(spend[name], clicks[name]).
Python 3
spend = {"Search": 1250.0, "Social": 980.5, "Video": 2100.0, "Display": 0.0}
clicks = {"Search": 820, "Social": 610, "Video": 1750, "Display": 0}


def cpc(spend, clicks):
    return 0


cpc_by_campaign = {}
print(cpc_by_campaign)
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