Skip to content

01. Python basics — Exercises

These exercises practice every idea of the Python basics lesson. They use small values typed by hand from the course datasets: sensor readings, products, stores and customers.

How to work:

  1. Read the task and the expected output.
  2. Copy the starter code into a script (for example exercise.py) and replace each to-do comment with your code.
  3. Run the script with python exercise.py. Compare your output with the expected output.
  4. Stuck? Open one hint at a time. Open the solution only after a real attempt.

Each solution ends with assert statements. An assert checks a condition: assert total == 7 does nothing when the condition is True and stops the script with an AssertionError when it is False. Add the same checks to your own code.

Warm-up

A sensor gateway prints a start-up message. Store the sensor id "S1", the reading interval 10 (minutes) and the status "ok" in variables. Build each of the three lines below as a string with an f-string, store it in a variable, then print it. Use the variables, not the literal values, inside the f-strings.

Expected output
Sensor S1 online
Interval: 10 minutes
Status: ok
Starter
sensor_id = "S1"
interval_minutes = 10
status = "ok"
# TODO: build line_1, line_2 and line_3 with f-strings
# TODO: print the three lines
Hint 1

An f-string puts a value inside text: f"Status: {status}".

Hint 2

line_1 = f"Sensor {sensor_id} online" builds the first line. print(line_1) shows it.

Solution
sensor_id = "S1"
interval_minutes = 10
status = "ok"
line_1 = f"Sensor {sensor_id} online"
line_2 = f"Interval: {interval_minutes} minutes"
line_3 = f"Status: {status}"
print(line_1)
print(line_2)
print(line_3)
assert line_1 == "Sensor S1 online"
assert line_2 == "Interval: 10 minutes"
assert line_3 == "Status: ok"
Output
Sensor S1 online
Interval: 10 minutes
Status: ok

How it works:

  1. Three assignments give names to the three values.
  2. Each f-string replaces the name in curly braces with its value. The int 10 becomes the text 10.
  3. Storing each line in a variable lets the asserts check the exact text that the script prints.

Alternative: pass several arguments to print(). It puts one space between them, so you need no f-string.

sensor_id = "S1"
interval_minutes = 10
status = "ok"
print("Sensor", sensor_id, "online")
print("Interval:", interval_minutes, "minutes")
print("Status:", status)
Output
Sensor S1 online
Interval: 10 minutes
Status: ok
Warm-up

This record starts with product P001 from data/products.csv and adds three fields that are not in that file: sales_lines (its number of lines in data/sales.csv), in_stock and discontinued_on. Print the name of each field and its type, one per line, in the order shown.

Expected output
product_id <class 'str'>
unit_price <class 'float'>
sales_lines <class 'int'>
in_stock <class 'bool'>
discontinued_on <class 'NoneType'>
Starter
product_id = "P001"
unit_price = 79.99
sales_lines = 1375
in_stock = True
discontinued_on = None
# TODO: print each name and its type
Hint 1

type(value) returns the type. print() can show it next to a label.

Hint 2

The first line is print("product_id", type(product_id)).

Solution
product_id = "P001"
unit_price = 79.99
sales_lines = 1375
in_stock = True
discontinued_on = None
print("product_id", type(product_id))
print("unit_price", type(unit_price))
print("sales_lines", type(sales_lines))
print("in_stock", type(in_stock))
print("discontinued_on", type(discontinued_on))
assert type(unit_price) is float
assert type(sales_lines) is int
assert discontinued_on is None
Output
product_id <class 'str'>
unit_price <class 'float'>
sales_lines <class 'int'>
in_stock <class 'bool'>
discontinued_on <class 'NoneType'>

How it works:

  1. Quotes make "P001" a str.
  2. 79.99 has a decimal point, so it is a float. 1375 has none, so it is an int.
  3. True is a bool. None is the only value of the type NoneType.
  4. The asserts use is to compare types, because each type exists as exactly one object in memory.

Alternative: in the REPL, type each name alone. The REPL echoes the value, and type(name) echoes the type. This is the quickest way to inspect a value you do not know.

Warm-up

A sensor reports 21.5 °C. Convert it to Fahrenheit with °F = °C × 9 / 5 + 32. Print the sentence below, with the Fahrenheit value rounded to 1 decimal.

Expected output
21.5 °C is 70.7 °F
Starter
celsius = 21.5
# TODO: convert to Fahrenheit and print the sentence
Hint 1

Write the formula as Python: celsius * 9 / 5 + 32. Precedence makes Python multiply and divide before it adds.

Hint 2

In an f-string, {fahrenheit:.1f} shows the value with 1 decimal.

Solution
celsius = 21.5
fahrenheit = celsius * 9 / 5 + 32
print(f"{celsius} °C is {fahrenheit:.1f} °F")
assert round(fahrenheit, 1) == 70.7
Output
21.5 °C is 70.7 °F

How it works:

  1. celsius * 9 is 193.5. Dividing by 5 gives 38.7. Adding 32 gives 70.7.
  2. * and / run before +, so no parentheses are needed.
  3. :.1f formats the float with exactly 1 decimal.

Alternative: print(celsius, "°C is", round(fahrenheit, 1), "°F") gives the same line with round() and plain print() arguments.

Warm-up

Predict the output: write down what each line prints. Then run the code and compare.

Acceptance criteria:

  • Write your prediction for every line before you run the code.
  • Run the code. Your prediction matches the Output in the solution, line by line.
  • For each line you got wrong, you can name the rule that explains it.
Starter
print(23 / 4)
print(23 // 4)
print(23 % 4)
print(24 / 4)
print(3 ** 4)
print(-23 // 4)
# TODO: write your prediction for each line before you run it
Hint 1

/ always returns a float. // and % with two int operands return an int.

Hint 2

// rounds down, toward minus infinity. −5.75 rounded down is −6.

Solution
print(23 / 4)
print(23 // 4)
print(23 % 4)
print(24 / 4)
print(3 ** 4)
print(-23 // 4)
assert 23 // 4 * 4 + 23 % 4 == 23
assert -23 // 4 == -6
Output
5.75
5
3
6.0
81
-6

How it works:

  1. 23 / 4 is the exact quotient, 5.75.
  2. 23 // 4 is 5: four fits into 23 five whole times.
  3. 23 % 4 is 3, the remainder: 23 − 5 × 4 = 3.
  4. 24 / 4 is 6.0, not 6. / gives a float even when the division is exact.
  5. 3 ** 4 is 3 × 3 × 3 × 3 = 81.
  6. -23 / 4 is −5.75. Floor division rounds down to −6, not toward zero to −5.

Alternative: the first assert is the rule that links // and %. You can test any pair of numbers with it in the REPL.

Warm-up

A CSV file gives you two fields as text: the units sold "1375" and the unit price "79.99". Convert them to numbers and print the revenue (units × price).

Expected output
Revenue: 109986.25
Starter
units_text = "1375"
price_text = "79.99"
# TODO: convert both values and print the revenue
Hint 1

A count is a whole number, so use int(). A price has decimals, so use float().

Hint 2

units_text * price_text raises a TypeError. Convert first, then multiply.

Solution
units_text = "1375"
price_text = "79.99"
units = int(units_text)
price = float(price_text)
revenue = units * price
print("Revenue:", revenue)
assert type(units) is int
assert type(revenue) is float
assert round(revenue, 2) == 109986.25
Output
Revenue: 109986.25

How it works:

  1. int("1375") reads the digits and returns the integer 1375.
  2. float("79.99") returns the float 79.99.
  3. An int times a float gives a float.

Alternative: float(units_text) also works for the units, but the result would be 1375.0. Keep counts as int, so the type tells the reader that the value is a count.

M01-W06 · Fix the bug: text plus a number

Section titled “M01-W06 · Fix the bug: text plus a number”
Warm-up

Fix the bug: this code should print a label and a count, but it crashes.

units_sold = 1375
print("Units sold: " + units_sold)
Output
TypeError: can only concatenate str (not "int") to str

Change the second line so that it prints:

Expected output
Units sold: 1375
Starter
units_sold = 1375
print("Units sold: " + units_sold) # TODO: fix this line
Hint 1

Read the last line of the error. + between a str and an int is not allowed.

Hint 2

Turn the number into text with str(), or let an f-string do it.

Solution
units_sold = 1375
print("Units sold: " + str(units_sold))
assert str(units_sold) == "1375"
Output
Units sold: 1375

How it works:

  1. With a string on the left, + means “join two strings”. The right side is an int, so Python raises a TypeError.
  2. str(units_sold) makes the text "1375". Now both sides are strings, and + joins them.

Alternative: the f-string print(f"Units sold: {units_sold}") converts the value for you. Passing two arguments also works: print("Units sold:", units_sold).

M01-W07 · Predict the output: truthy or falsy

Section titled “M01-W07 · Predict the output: truthy or falsy”
Warm-up

Predict the output: for each value, decide if bool() gives True or False.

Acceptance criteria:

  • Write your prediction for every line before you run the code.
  • Run the code. Your prediction matches the Output in the solution, line by line.
  • For each line you got wrong, you can name the rule that explains it.
Starter
print(bool(0), bool(0.0), bool(""), bool(" "), bool("0"), bool(None), bool(-1.5))
# TODO: predict the seven values before you run the line
Hint 1

The falsy values of this module are False, 0, 0.0, "" and None.

Hint 2

A string is falsy only when it is empty. A space is a character.

Solution
print(bool(0), bool(0.0), bool(""), bool(" "), bool("0"), bool(None), bool(-1.5))
assert bool(" ") is True
assert bool(-1.5) is True
Output
False False False True True False True

How it works:

  1. 0 and 0.0 are zero, so they are falsy.
  2. "" is the empty string, so it is falsy.
  3. " " holds one space and "0" holds one digit. Neither is empty, so both are truthy.
  4. None is falsy.
  5. Every number except zero is truthy, negative numbers too.

Alternative: test one value at a time in the REPL, for example >>> bool(" ").

Warm-up

Refactor: this code works, but nobody can tell what it means. The numbers are the floor areas of store S01 (Chicago, 2850 m²) and store S03 (Detroit, 1420 m²). Rename the variables, add one comment and print the sentence below.

Expected output
Chicago (S01) is 1430 m² larger than Detroit (S03).
Starter
a = 2850
b = 1420
c = a - b
print(c)
# TODO: use clear names, add a comment and print the full sentence
Hint 1

Good names say what the value is and, if useful, its unit: chicago_size_sqm.

Hint 2

An f-string builds the sentence: f"Chicago (S01) is {difference} m² larger ...".

Solution
# Floor areas from data/stores.csv, in square meters.
chicago_size_sqm = 2850
detroit_size_sqm = 1420
difference_sqm = chicago_size_sqm - detroit_size_sqm
print(f"Chicago (S01) is {difference_sqm} m² larger than Detroit (S03).")
assert difference_sqm == 1430
Output
Chicago (S01) is 1430 m² larger than Detroit (S03).

How it works:

  1. Each name says what the number is and gives its unit (_sqm).
  2. The comment gives the source and the unit, which the code cannot show.
  3. The result is the same as before. Only the readability changed. That is what a refactor is: a change to the structure of code that keeps its behavior.

Alternative: print("Chicago (S01) is", difference_sqm, "m² larger than Detroit (S03).") gives the same sentence without an f-string.

Core

The first three lines of data/readings.txt are 21.0, 21.9 and 21.4. You receive them as text. Convert them, compute the average and print it with 2 decimals.

Expected output
Average of 3 readings: 21.43 °C
Starter
line_1 = "21.0"
line_2 = "21.9"
line_3 = "21.4"
# TODO: convert, average and print
Hint 1

Convert each line with float() and store the number in a new variable.

Hint 2

Add the three numbers inside parentheses, then divide by 3. Format with :.2f.

Solution
import math
line_1 = "21.0"
line_2 = "21.9"
line_3 = "21.4"
reading_1 = float(line_1)
reading_2 = float(line_2)
reading_3 = float(line_3)
count = 3
average = (reading_1 + reading_2 + reading_3) / count
print(f"Average of {count} readings: {average:.2f} °C")
assert math.isclose(average, 21.433333333333334)
Output
Average of 3 readings: 21.43 °C

How it works:

  1. float() turns each line of text into a number.
  2. The parentheses make Python add before it divides.
  3. The count is a variable, so the f-string and the formula use the same number.
  4. The assert compares floats with math.isclose(), not ==.

Alternative: convert inside the formula: (float(line_1) + float(line_2) + float(line_3)) / 3. It is shorter but harder to debug, because you cannot print one converted value on its own.

M01-C02 · Fix the bug: the average is too high

Section titled “M01-C02 · Fix the bug: the average is too high”
Core

Fix the bug: lines 6 to 8 of data/readings.txt hold 22.0, 22.5 and 22.9. The code in the starter prints an “average” of 52.13 °C, which is far above every reading. Fix it so that it prints:

Expected output
Average: 22.47 °C
Starter
r1 = 22.0
r2 = 22.5
r3 = 22.9
average = r1 + r2 + r3 / 3 # TODO: fix this formula
print(f"Average: {average:.2f} °C")
Hint 1

An average must lie between the smallest and the largest value. Which operator runs first in the formula?

Hint 2

/ runs before +. Group the sum with parentheses.

Solution
r1 = 22.0
r2 = 22.5
r3 = 22.9
average = (r1 + r2 + r3) / 3
print(f"Average: {average:.2f} °C")
assert min(r1, r2, r3) <= average <= max(r1, r2, r3)
Output
Average: 22.47 °C

How it works:

  1. The buggy line computes 22.0 + 22.5 + (22.9 / 3), which is 52.13.
  2. The parentheses make Python add the three readings first (67.4), then divide by 3.
  3. The assert checks a rule that every average obeys: it lies between the minimum and the maximum. A sanity check like this catches many formula bugs.

Alternative: split the formula into two named steps, total = r1 + r2 + r3 and average = total / 3. Two short lines leave no room for a precedence mistake.

Core

An order line from data/sales.csv: 2 Espresso Machines at 349.00 USD each, with a discount of 0.1 (10%). Print the gross amount, the discount amount and the revenue, each with 2 decimals.

Expected output
Gross: 698.00 USD
Discount: 69.80 USD
Revenue: 628.20 USD
Starter
quantity = 2
unit_price = 349.00
discount = 0.1
# TODO: compute gross, discount amount and revenue, then print them
Hint 1

Gross is quantity × unit price. The discount amount is gross × discount.

Hint 2

Revenue is gross minus the discount amount. Use :.2f in each f-string.

Solution
import math
quantity = 2
unit_price = 349.00
discount = 0.1
gross = quantity * unit_price
discount_amount = gross * discount
revenue = gross - discount_amount
print(f"Gross: {gross:.2f} USD")
print(f"Discount: {discount_amount:.2f} USD")
print(f"Revenue: {revenue:.2f} USD")
assert math.isclose(revenue, quantity * unit_price * (1 - discount))
assert math.isclose(revenue, 628.2)
Output
Gross: 698.00 USD
Discount: 69.80 USD
Revenue: 628.20 USD

How it works:

  1. gross is 2 × 349.0 = 698.0.
  2. discount_amount is 698.0 × 0.1 = 69.8.
  3. revenue is 698.0 − 69.8 = 628.2.
  4. The first assert checks the dataset formula, quantity × price × (1 − discount), against the step-by-step result.

Alternative: compute the revenue in one line with quantity * unit_price * (1 - discount). Use it when you do not need the gross and discount amounts.

Core

A warehouse ships 1129 Organic Cotton T-Shirts. A box holds 24. Print the number of full boxes, the units left over and the total number of boxes to ship (a partly filled box still ships).

Expected output
Full boxes: 47
Units left over: 1
Boxes to ship: 48
Starter
units = 1129
box_size = 24
# TODO: compute full boxes, leftover units and boxes to ship
Hint 1

// counts the full boxes. % gives what is left.

Hint 2

One extra box ships when the leftover is more than 0. A comparison gives True or False, and True counts as 1 in arithmetic.

Solution
units = 1129
box_size = 24
full_boxes = units // box_size
left_over = units % box_size
boxes_to_ship = full_boxes + (left_over > 0)
print("Full boxes:", full_boxes)
print("Units left over:", left_over)
print("Boxes to ship:", boxes_to_ship)
assert full_boxes * box_size + left_over == units
assert boxes_to_ship == 48
Output
Full boxes: 47
Units left over: 1
Boxes to ship: 48

How it works:

  1. 1129 // 24 is 47 full boxes (47 × 24 = 1128).
  2. 1129 % 24 is the 1 unit that remains.
  3. left_over > 0 is True. In arithmetic, True counts as 1, so boxes_to_ship is 48.
  4. The first assert rebuilds the total from the parts.

Alternative: ceiling division rounds a division up instead of down. The idiom (units + box_size - 1) // box_size also gives 48. It adds just enough to push any partial box over the next multiple.

units = 1129
box_size = 24
print("Boxes to ship:", (units + box_size - 1) // box_size)
Output
Boxes to ship: 48

M01-C05 · Predict the output: strings and numbers

Section titled “M01-C05 · Predict the output: strings and numbers”
Core

Predict the output of each line. Pay attention to the type of each operand.

Acceptance criteria:

  • Write your prediction for every line before you run the code.
  • Run the code. Your prediction matches the Output in the solution, line by line.
  • For each line you got wrong, you can name the rule that explains it.
Starter
print("3" + "4")
print("3" * 4)
print(int("3") + int("4"))
print(float("3") * 4)
print(str(3) + str(4.0))
print("-" * 10)
# TODO: predict each line before you run the code
Hint 1

With strings, + joins and * repeats. With numbers, they add and multiply.

Hint 2

str(4.0) is "4.0", not "4".

Solution
print("3" + "4")
print("3" * 4)
print(int("3") + int("4"))
print(float("3") * 4)
print(str(3) + str(4.0))
print("-" * 10)
assert "3" + "4" == "34"
assert "3" * 4 == "3333"
assert float("3") * 4 == 12.0
Output
34
3333
7
12.0
34.0
----------

How it works:

  1. "3" + "4" joins two strings into "34".
  2. "3" * 4 repeats the string 4 times.
  3. After int(), + adds: 3 + 4 = 7.
  4. float("3") is 3.0, and 3.0 × 4 is 12.0, a float.
  5. str(3) is "3" and str(4.0) is "4.0". Joined, they make "34.0".
  6. "-" * 10 repeats a dash 10 times. Scripts often print a line like this to separate parts of a report.

Alternative: test each expression in the REPL. The REPL shows strings with quotes ('34') and numbers without, which makes the type visible.

Core

Fix the bug: a checkout script reads a quantity with input(). Here the reply "4" is typed in by hand. The script crashes:

quantity_text = "4" # what input() returns when the clerk types 4
unit_price = 34.99
total = quantity_text * unit_price
print(total)
Output
TypeError: can't multiply sequence by non-int of type 'float'

Fix it so that it prints:

Expected output
Total for 4 yoga mats: 139.96 USD
Starter
quantity_text = "4" # what input() returns when the clerk types 4
unit_price = 34.99
total = quantity_text * unit_price # TODO: fix the bug
print(total) # TODO: print the full sentence
Hint 1

What type does input() return? A string is a sequence (an ordered series) of characters, which is the word in the error.

Hint 2

Convert the reply with int() before you multiply. Show the total with :.2f.

Solution
import math
quantity_text = "4" # what input() returns when the clerk types 4
unit_price = 34.99
quantity = int(quantity_text)
total = quantity * unit_price
print(f"Total for {quantity} yoga mats: {total:.2f} USD")
assert type(quantity) is int
assert math.isclose(total, 139.96)
Output
Total for 4 yoga mats: 139.96 USD

How it works:

  1. input() always returns a str, so quantity_text is "4".
  2. A string times an int repeats the string. A string times a float has no meaning, so Python raises a TypeError.
  3. int(quantity_text) makes the number 4. Now * multiplies.

Alternative: convert at the moment you read: quantity = int(input("Quantity: ")). Then no text version of the value exists that you could use by mistake.

Core

The valid range of a room sensor is 19.0 °C to 23.0 °C, inclusive. Check four readings and print one line for each.

Expected output
21.7 in range: True
18.4 in range: False
23.0 in range: True
25.1 in range: False
Starter
low = 19.0
high = 23.0
reading_a = 21.7
reading_b = 18.4
reading_c = 23.0
reading_d = 25.1
# TODO: print each reading and whether it is in range
Hint 1

“Inclusive” means that 19.0 and 23.0 are valid. Use <=, not <.

Hint 2

A chained comparison checks both limits at once: low <= reading_a <= high.

Solution
low = 19.0
high = 23.0
reading_a = 21.7
reading_b = 18.4
reading_c = 23.0
reading_d = 25.1
print(reading_a, "in range:", low <= reading_a <= high)
print(reading_b, "in range:", low <= reading_b <= high)
print(reading_c, "in range:", low <= reading_c <= high)
print(reading_d, "in range:", low <= reading_d <= high)
assert (low <= reading_c <= high) is True
assert (low <= reading_d <= high) is False
Output
21.7 in range: True
18.4 in range: False
23.0 in range: True
25.1 in range: False

How it works:

  1. low <= reading_a <= high means low <= reading_a and reading_a <= high.
  2. 23.0 is exactly the upper limit. With <=, it is valid.
  3. The limits are variables. If the sensor specification changes, you change one line.

Alternative: write the two halves with and: reading_a >= low and reading_a <= high. It gives the same result, but the chained form reads like the mathematical notation 19.0 ≤ x ≤ 23.0. Module 03 replaces the four similar lines with a loop.

Core

A retention team uses this rule: a customer is high risk when the contract is month-to-month and the customer has 3 or more support tickets or no autopay. Check the customer below and print each part of the rule and the result.

Expected output
Month-to-month: False
Many tickets: False
No autopay: True
High risk: False
Starter
contract = "one-year"
support_tickets = 1
has_autopay = 0
# TODO: build the three flags and combine them
Hint 1

contract == "month-to-month" gives the first flag. has_autopay == 0 gives the third.

Hint 2

and runs before or. The rule means “month-to-month and (many tickets or no autopay)”, so you need parentheses.

Solution
contract = "one-year"
support_tickets = 1
has_autopay = 0
is_monthly = contract == "month-to-month"
many_tickets = support_tickets >= 3
no_autopay = has_autopay == 0
high_risk = is_monthly and (many_tickets or no_autopay)
print("Month-to-month:", is_monthly)
print("Many tickets:", many_tickets)
print("No autopay:", no_autopay)
print("High risk:", high_risk)
assert high_risk is False
assert (is_monthly and many_tickets or no_autopay) is True # the version without ()
Output
Month-to-month: False
Many tickets: False
No autopay: True
High risk: False

How it works:

  1. Each comparison gives one bool with a clear name.
  2. The parentheses group the two alternatives. A one-year contract fails the first part, so the customer is not high risk.
  3. The last assert shows the bug you avoid: without parentheses, Python reads (is_monthly and many_tickets) or no_autopay, which is True for this customer.

Alternative: not has_autopay also gives the third flag, because 0 is falsy. has_autopay == 0 states the meaning more directly for a 0/1 column.

M01-C09 · Interpret: tests for a missing value

Section titled “M01-C09 · Interpret: tests for a missing value”
Core

Interpret a result: a discount is missing, so it is None. Run the code below and explain each line. Then answer: which test still works when a real discount of 0.0 arrives?

Expected output
True
False
False
<class 'NoneType'>
Starter
discount = None
print(discount is None)
print(discount == 0)
print(bool(discount))
print(type(discount))
# TODO: explain each result; then set discount = 0.0 and run again
Hint 1

None is a value of its own type. It is not equal to 0.

Hint 2

Run the same four lines with discount = 0.0. Which line changes its meaning?

Solution
discount = None
print(discount is None)
print(discount == 0)
print(bool(discount))
print(type(discount))
assert (discount is None, discount == 0, bool(discount)) == (True, False, False)
Output
True
False
False
<class 'NoneType'>

Now the same lines with a real discount of zero:

discount = 0.0
print(discount is None)
print(discount == 0)
print(bool(discount))
print(type(discount))
assert (discount is None, discount == 0, bool(discount)) == (False, True, False)
Output
False
True
False
<class 'float'>

How it works:

  1. discount is None is True only for None. It is the correct test for a missing value.
  2. discount == 0 is False for None, because None is not a number. It is True for 0.0.
  3. bool(discount) is False for both. Both values are falsy, so bool() cannot tell “missing” from “zero”.
  4. type() shows NoneType for the missing value and float for the real one.

The answer: discount is None is the only test that keeps the two cases apart. is not None is its opposite. The asserts pin down all three results for both cases.

Alternative: type(discount) is float also tells the cases apart, but is None is shorter and is the standard Python idiom.

M01-C10 · Choose and justify: compare a money total

Section titled “M01-C10 · Choose and justify: compare a money total”
Core

Choose a method and justify it: a basket holds Wireless Earbuds (79.99) and a Running Socks 3-Pack (14.99). The invoice says 94.98. Compare the computed total with the invoice in three ways, print the three results, then choose the method you would use in a data check.

Expected output
Total: 94.97999999999999
== invoice: False
rounded == invoice: True
isclose: True
Starter
import math
earbuds = 79.99
socks = 14.99
invoice = 94.98
total = earbuds + socks
# TODO: print the total, then the result of ==, of round(total, 2) == and of math.isclose
Hint 1

round(total, 2) returns a float rounded to 2 decimals. Compare that with the invoice.

Hint 2

math.isclose(a, b) is True when the two values agree to about 9 significant digits.

Solution
import math
earbuds = 79.99
socks = 14.99
invoice = 94.98
total = earbuds + socks
print("Total:", total)
print("== invoice:", total == invoice)
print("rounded == invoice:", round(total, 2) == invoice)
print("isclose:", math.isclose(total, invoice))
assert math.isclose(total, invoice)
Output
Total: 94.97999999999999
== invoice: False
rounded == invoice: True
isclose: True

How it works:

  1. The binary forms of 79.99 and 14.99 are not exact, so their sum is a hair below 94.98.
  2. == compares every bit and reports False, although the money is correct.
  3. Rounding to cents removes the error, so the rounded value equals the invoice.
  4. math.isclose() accepts a tiny relative difference, so it reports True.

Choice: use math.isclose() for a general check between two computed floats. Its tolerance is relative, so it suits sensor readings and millions of dollars alike. Near zero, a relative tolerance is too strict: pass abs_tol, as in math.isclose(x, 0, abs_tol=1e-9). Rounding to 2 decimals is a good choice when the rule is explicitly “equal to the cent”, as on an invoice. Never use == on computed floats.

Alternative: work in whole cents: 7999 + 1499 == 9498 is exact, because int arithmetic has no rounding error. Payment systems do this.

Core

Print this receipt for an order at store S07 (New York). Use the end argument of print() for the date line, the sep argument to join the date parts with dashes, and an f-string with :.2f for the amounts.

Expected output
Store S07 (New York)
Order date: 2024-05-01
3 x Non-Slip Yoga Mat @ 34.99 = 104.97 USD
--------------------------
Starter
store_id = "S07"
city = "New York"
product = "Non-Slip Yoga Mat"
quantity = 3
unit_price = 34.99
# TODO: print the four lines
Hint 1

print("Order date: ", end="") prints the label and stays on the same line.

Hint 2

print("2024", "05", "01", sep="-") prints 2024-05-01. The last line is "-" * 26.

Solution
store_id = "S07"
city = "New York"
product = "Non-Slip Yoga Mat"
quantity = 3
unit_price = 34.99
line_total = quantity * unit_price
print(f"Store {store_id} ({city})")
print("Order date: ", end="")
print("2024", "05", "01", sep="-")
print(f"{quantity} x {product} @ {unit_price:.2f} = {line_total:.2f} USD")
print("-" * 26)
assert round(line_total, 2) == 104.97
Output
Store S07 (New York)
Order date: 2024-05-01
3 x Non-Slip Yoga Mat @ 34.99 = 104.97 USD
--------------------------

How it works:

  1. The f-string puts the store id and the city into the first line.
  2. end="" replaces the line break after "Order date: " with nothing, so the next print() continues the same line.
  3. sep="-" puts a dash between the three date parts instead of a space.
  4. :.2f shows both amounts with exactly 2 decimals, which hides the float error in line_total.

Alternative: store the date parts as numbers (year = 2024, month = 5, day = 1). Then one f-string gives the same line: f"Order date: {year}-{month:02d}-{day:02d}". The spec :02d pads a number to 2 digits. Module 02 shows format specs in detail.

Core

Choose a method and justify it: each case below needs a whole number. Pick round(), int() or // for each and print the results.

  • A dashboard shows the temperature 21.7 °C in whole degrees.
  • A session lasted 135 minutes. How many full hours is that?
  • A customer is 42.9 years old. How many full years has the customer lived?
Expected output
Display temperature: 22
Full hours: 2
Completed years: 42
Starter
temperature = 21.7
session_minutes = 135
age_years = 42.9
# TODO: pick round(), int() or // for each value and print it
Hint 1

Ask for each case: do I want the nearest whole number, or the number of complete units?

Hint 2

round() gives the nearest. // counts complete units of a divisor. int() drops the decimals of a float.

Solution
temperature = 21.7
session_minutes = 135
age_years = 42.9
display_temperature = round(temperature)
full_hours = session_minutes // 60
completed_years = int(age_years)
print("Display temperature:", display_temperature)
print("Full hours:", full_hours)
print("Completed years:", completed_years)
assert display_temperature == 22
assert full_hours == 2
assert completed_years == 42
Output
Display temperature: 22
Full hours: 2
Completed years: 42

How it works:

  1. Temperature: a display should be as close to the truth as possible. 21.7 is closer to 22 than to 21, so use round(). int() would show 21.
  2. Hours: you count complete units of 60 minutes, so // is the natural tool. It also keeps the value an int.
  3. Age: a person aged 42.9 has completed 42 years. int() drops the decimals. round() would give 43, which is wrong for an age.

Alternative: int(session_minutes / 60) also gives 2 for positive values. // is clearer and avoids the float step. For negative values the two differ: int() cuts toward zero and // rounds down.

M01-X01 · Summarize a batch of raw readings

Section titled “M01-X01 · Summarize a batch of raw readings”
Challenge

Lines 1 to 5 of data/readings.txt arrive as raw text. A line read from a file still ends with the line break \n, as in the last value. Convert all five values. Then print the report below: count, minimum, maximum, range (max − min), mean in °C and °F, the drift from the first to the last reading, and whether every reading lies in the valid range 19.0 °C to 23.0 °C.

Expected output
Readings: 5
Min: 21.0 °C
Max: 22.1 °C
Range: 1.1 °C
Mean: 21.62 °C (70.92 °F)
Drift first to last: +1.1 °C
All in range 19.0-23.0 °C: True
Starter
raw_1 = "21.0"
raw_2 = "21.9"
raw_3 = "21.4"
raw_4 = "21.7"
raw_5 = "22.1\n"
low_limit = 19.0
high_limit = 23.0
# TODO: convert the five values
# TODO: compute min, max, range, mean in °C and °F, and the drift
# TODO: compute the in-range flag and print the report
Hint 1

float() ignores spaces and line breaks around the number, so float("22.1\n") works. min() and max() accept any number of arguments.

Hint 2

Every reading is in range when the lowest one is at least the low limit and the highest one is at most the high limit. You do not need five comparisons.

Hint 3

The difference of two floats can carry a tiny error: 22.1 - 21.0 is 1.1000000000000014. Format the range with :.1f to hide it, and the drift with :+.1f, which always shows the sign.

Solution
import math
raw_1 = "21.0"
raw_2 = "21.9"
raw_3 = "21.4"
raw_4 = "21.7"
raw_5 = "22.1\n"
low_limit = 19.0
high_limit = 23.0
r1 = float(raw_1)
r2 = float(raw_2)
r3 = float(raw_3)
r4 = float(raw_4)
r5 = float(raw_5) # float() ignores the trailing line break
count = 5
lowest = min(r1, r2, r3, r4, r5)
highest = max(r1, r2, r3, r4, r5)
spread = highest - lowest
mean_c = (r1 + r2 + r3 + r4 + r5) / count
mean_f = mean_c * 9 / 5 + 32
drift = r5 - r1 # positive: the room got warmer
all_in_range = low_limit <= lowest and highest <= high_limit
print("Readings:", count)
print(f"Min: {lowest:.1f} °C")
print(f"Max: {highest:.1f} °C")
print(f"Range: {spread:.1f} °C")
print(f"Mean: {mean_c:.2f} °C ({mean_f:.2f} °F)")
print(f"Drift first to last: {drift:+.1f} °C")
print(f"All in range {low_limit}-{high_limit} °C:", all_in_range)
assert lowest <= mean_c <= highest
assert math.isclose(mean_c, 21.62)
assert math.isclose(spread, 1.1)
assert all_in_range is True
Output
Readings: 5
Min: 21.0 °C
Max: 22.1 °C
Range: 1.1 °C
Mean: 21.62 °C (70.92 °F)
Drift first to last: +1.1 °C
All in range 19.0-23.0 °C: True

How it works:

  1. float() converts each line. It strips the \n of the last line for you.
  2. min() and max() return the smallest and largest of their arguments. The range is their difference.
  3. The mean is the sum, in parentheses, divided by the count. The Fahrenheit formula then converts the mean. This gives the same result as averaging five converted values, because the formula is linear.
  4. The drift compares the last reading with the first. The format spec :+.1f shows +1.1, so a reader sees the direction at once.
  5. If the lowest reading is inside the range and the highest one is too, every reading between them is inside. Two comparisons check five values.
  6. The asserts check the mean against its limits and the computed values against known results, with math.isclose() for floats.

Watch out: do not name your results min and max. That hides the built-in functions with the same names. After min = 21.0, a call to min(...) fails with TypeError: 'float' object is not callable.

Alternative: check each reading on its own with chained comparisons and combine the five results with and: low_limit <= r1 <= high_limit and low_limit <= r2 <= high_limit and .... It is longer, but it still works when you need to know which reading failed. Module 04 stores the readings in a list, and module 03 checks them in a loop.

M01-X02 · From clock time to reading number and back

Section titled “M01-X02 · From clock time to reading number and back”
Challenge

Each sensor in data/sensors.csv logs every 10 minutes from 2024-05-01 00:00. Reading number 0 is at that moment. Find the reading number for 2024-05-09 15:20. Then convert the number back to a date and time to check your work.

Expected output
Readings per day: 144
Reading number for 2024-05-09 15:20: 1244
Check: reading 1244 is at 2024-05-09 15:20
Starter
interval_minutes = 10
day_of_month = 9
hour = 15
minute = 20
# TODO: readings per day
# TODO: reading number = full days * readings per day + readings since midnight
# TODO: convert the number back to day, hour and minute and print the check
Hint 1

A day has 24 × 60 minutes. Divide by the interval to get the readings per day.

Hint 2

May 9 is 8 full days after May 1. Minutes since midnight are hour * 60 + minute.

Hint 3

To go back, use // and % twice: first with the readings per day, then with 60 minutes. Show two-digit numbers with :02d.

Solution
interval_minutes = 10
day_of_month = 9
hour = 15
minute = 20
# Forward: clock time -> reading number.
readings_per_day = 24 * 60 // interval_minutes
full_days = day_of_month - 1
minutes_since_midnight = hour * 60 + minute
reading_number = (
full_days * readings_per_day + minutes_since_midnight // interval_minutes
)
label = f"2024-05-{day_of_month:02d} {hour:02d}:{minute:02d}"
print("Readings per day:", readings_per_day)
print(f"Reading number for {label}: {reading_number}")
# Back: reading number -> clock time.
days_back = reading_number // readings_per_day
minutes_back = reading_number % readings_per_day * interval_minutes
hour_back = minutes_back // 60
minute_back = minutes_back % 60
print(
f"Check: reading {reading_number} is at "
f"2024-05-{1 + days_back:02d} {hour_back:02d}:{minute_back:02d}"
)
assert readings_per_day == 144
assert reading_number == 1244
assert (1 + days_back, hour_back, minute_back) == (day_of_month, hour, minute)
Output
Readings per day: 144
Reading number for 2024-05-09 15:20: 1244
Check: reading 1244 is at 2024-05-09 15:20

How it works:

  1. 24 * 60 // 10 is 144 readings per day. * and // have the same precedence and run left to right.
  2. May 9 is 8 full days after May 1: 8 × 144 = 1152 readings.
  3. 15:20 is 920 minutes after midnight, which is 92 readings. 1152 + 92 = 1244.
  4. Going back, 1244 // 144 is 8 full days and 1244 % 144 is 92 readings, which is 920 minutes.
  5. 920 // 60 is 15 hours and 920 % 60 is 20 minutes.
  6. Parentheses around a long expression let it continue on the next line. Two f-strings next to each other join into one string.
  7. The last assert compares three values at once. The parentheses build a tuple, a fixed group of values that module 04 explains.

Alternative: module 09 shows datetime, which does date arithmetic for you: start + timedelta(minutes=10 * 1244). Knowing the // and % method still helps, because many logs store time as plain counts of seconds or ticks.

M01-X03 · Refactor and extend: the margin of a discounted order

Section titled “M01-X03 · Refactor and extend: the margin of a discounted order”
Challenge

Refactor: this script computes the margin of the 55-inch 4K Smart TV (product P003: unit cost 845.00, unit price 1299.00). It prints 454.0 34.9, and nobody knows what these numbers mean.

Rewrite it with clear names, comments and a readable report. Then extend it: a sales line sells 2 units of P003 at a discount of 0.2 (20%). Report the margin before and after the discount, and flag whether the discounted margin rate (margin ÷ selling price) falls below the 30% that the finance team sets as a minimum.

Expected output
Product: 55-inch 4K Smart TV (P003)
Unit cost: 845.00 USD
List price: 1299.00 USD
Margin at list price: 454.00 USD per unit (34.9%)
Order line: 2 units at 20% discount
Discounted price: 1039.20 USD
Line revenue: 2078.40 USD
Line margin: 388.40 USD (18.7%)
Margin rate below 30%: True
Starter
a=845.0
b=1299.0
c=b-a
d=c/b*100
print(c,round(d,1))
# TODO: rewrite with clear names, comments, spaces around operators and a clear report
# TODO: extend: 2 units at a 0.2 discount; line revenue, line margin, margin rate, flag
Hint 1

Decode the letters first: a is the cost, b the price, c the margin per unit and d the margin as a percentage of the price.

Hint 2

The discounted price is unit_price * (1 - discount). The line revenue is quantity × discounted price. The line cost is quantity × unit cost. The line margin is revenue minus cost.

Hint 3

Keep rates as fractions (0.187) and let the format spec :.1% multiply by 100 and add the % sign. Compare the fraction with 0.30.

Solution
import math
# Product P003 from data/products.csv. Money in USD.
product = "55-inch 4K Smart TV"
product_id = "P003"
unit_cost = 845.00 # what the shop pays the supplier
unit_price = 1299.00 # list price: what the customer pays without a discount
min_margin_rate = 0.30 # finance team's minimum, as a fraction of the selling price
# Margin at list price.
list_margin = unit_price - unit_cost
list_margin_rate = list_margin / unit_price
# One discounted sales line, shaped like a line of data/sales.csv.
quantity = 2
discount = 0.2
discounted_price = unit_price * (1 - discount)
line_revenue = quantity * discounted_price
line_cost = quantity * unit_cost
line_margin = line_revenue - line_cost
line_margin_rate = line_margin / line_revenue
below_minimum = line_margin_rate < min_margin_rate
print(f"Product: {product} ({product_id})")
print(f"Unit cost: {unit_cost:.2f} USD")
print(f"List price: {unit_price:.2f} USD")
print(f"Margin at list price: {list_margin:.2f} USD per unit ({list_margin_rate:.1%})")
print(f"Order line: {quantity} units at {discount:.0%} discount")
print(f"Discounted price: {discounted_price:.2f} USD")
print(f"Line revenue: {line_revenue:.2f} USD")
print(f"Line margin: {line_margin:.2f} USD ({line_margin_rate:.1%})")
print(f"Margin rate below {min_margin_rate:.0%}:", below_minimum)
assert math.isclose(list_margin, 454.0) # the refactor keeps the old numbers
assert round(list_margin_rate * 100, 1) == 34.9
assert math.isclose(line_margin, 388.4)
assert below_minimum is True
Output
Product: 55-inch 4K Smart TV (P003)
Unit cost: 845.00 USD
List price: 1299.00 USD
Margin at list price: 454.00 USD per unit (34.9%)
Order line: 2 units at 20% discount
Discounted price: 1039.20 USD
Line revenue: 2078.40 USD
Line margin: 388.40 USD (18.7%)
Margin rate below 30%: True

How it works:

  1. Refactor. Each name says what the value means. The comments give the source, the currency and the meaning of each price. Spaces around = and the operators follow PEP 8.
  2. List margin. 1299.00 − 845.00 = 454.00 per unit, which is 34.9% of the price. These are the two numbers that the cryptic script printed.
  3. Discount. 1299.00 × (1 − 0.2) = 1039.20 per unit. Two units bring 2078.40 in revenue and cost 1690.00.
  4. Line margin. 2078.40 − 1690.00 = 388.40, which is 18.7% of the line revenue.
  5. Flag. 0.187 < 0.30, so below_minimum is True. A 20% discount cuts the margin by more than half, because the discount comes out of the margin only: the cost stays the same.
  6. The asserts use math.isclose() for computed floats and check that the refactor kept the original numbers.

Alternative: some teams divide the margin by the cost instead of the price and call it the markup: 454 ÷ 845 is 53.7%. Write the definition you use in a comment, because the two words are often confused.

M01-X04 · Interpret: compare two stores fairly

Section titled “M01-X04 · Interpret: compare two stores fairly”
Challenge

Interpret a result: in data/sales.csv (2023-01-01 to 2024-12-31, 731 days), store S01 (Chicago, 2850 m²) has 2220 sales lines and store S12 (Denver, 1350 m²) has 868. S12 opened on 2023-06-15, so it was open for only 566 of those days. Compute the sales lines per day per 1,000 m² for each store. Print the results with 3 decimals and say which store sells more for its size and its time open.

Expected output
S01 Chicago: 1.066 lines per day per 1,000 m²
S12 Denver: 1.136 lines per day per 1,000 m²
S12 is busier for its size: True
Starter
s01_lines = 2220
s01_size_sqm = 2850
s01_days_open = 731
s12_lines = 868
s12_size_sqm = 1350
s12_days_open = 566
# TODO: compute lines per day per 1,000 m² for both stores
# TODO: print both rates and compare them
Hint 1

Divide the lines by the days open to get lines per day. Then divide by the size in thousands of square meters (size_sqm / 1000).

Hint 2

A comparison such as s12_rate > s01_rate gives the True or False for the last line.

Solution
s01_lines = 2220
s01_size_sqm = 2850
s01_days_open = 731
s12_lines = 868
s12_size_sqm = 1350
s12_days_open = 566
s01_rate = s01_lines / s01_days_open / (s01_size_sqm / 1000)
s12_rate = s12_lines / s12_days_open / (s12_size_sqm / 1000)
print(f"S01 Chicago: {s01_rate:.3f} lines per day per 1,000 m²")
print(f"S12 Denver: {s12_rate:.3f} lines per day per 1,000 m²")
print("S12 is busier for its size:", s12_rate > s01_rate)
assert s01_lines > s12_lines # raw totals favor Chicago
assert s12_rate > s01_rate # the fair rate favors Denver
Output
S01 Chicago: 1.066 lines per day per 1,000 m²
S12 Denver: 1.136 lines per day per 1,000 m²
S12 is busier for its size: True

How it works:

  1. Dividing by the days open removes the effect of S12’s late opening.
  2. Dividing by the size in thousands of m² removes the effect of Chicago’s larger floor.
  3. The parentheses around size_sqm / 1000 make Python compute the size first. Without them, lines / days / size * 1000 would also work, but the version with parentheses reads like the definition.
  4. Raw totals say Chicago sells 2.6 times as many lines. The fair rate says Denver is about 7% busier for its size and its time open.

Interpretation: a raw total mixes three effects: the store’s size, its time open and how well it sells. To compare performance, divide out the effects that are not performance. This idea, called normalization, returns in every analysis module of the course. One caveat: about 42% of all sales lines are online orders, which are only assigned to the store that ships them. Floor area does not drive those lines, so a stricter comparison counts only lines with channel == "store".

Alternative: compare sales lines per m² per year: multiply each daily rate by 365 and divide by 1000. The ranking stays the same, because both rates change by the same factor.

Challenge

Fix the bugs: a web shop receives an order form. Every field arrives as text. The code below has two bugs: it crashes on the first calculation, and after you fix that, it adds a gift-wrap fee that the customer did not ask for.

The fixed script prints:

Expected output
Quantity: 2
Gift wrap: False
Total: 259.98 USD
Starter
quantity_text = " 2 " # form field "quantity"
price_text = "129.99" # form field "price" (Trail Running Shoes)
gift_wrap_text = "no" # form field "gift wrap", "yes" or "no"
wrap_fee = 4.99
quantity = quantity_text # TODO: bug 1
unit_price = float(price_text)
wants_wrap = bool(gift_wrap_text) # TODO: bug 2
total = quantity * unit_price + wrap_fee * wants_wrap
print("Quantity:", quantity)
print("Gift wrap:", wants_wrap)
print(f"Total: {total:.2f} USD")
Hint 1

Bug 1: what is the type of quantity? int() ignores the spaces around the digits.

Hint 2

Bug 2: bool("no") is True, because "no" is not an empty string. Compare the text with "yes" instead.

Hint 3

wrap_fee * wants_wrap works because True counts as 1 and False as 0. It adds the fee only when wants_wrap is True.

Solution
import math
quantity_text = " 2 " # form field "quantity"
price_text = "129.99" # form field "price" (Trail Running Shoes)
gift_wrap_text = "no" # form field "gift wrap", "yes" or "no"
wrap_fee = 4.99
quantity = int(quantity_text) # fix 1: convert the text to a whole number
unit_price = float(price_text)
wants_wrap = gift_wrap_text == "yes" # fix 2: compare the text, do not use bool()
total = quantity * unit_price + wrap_fee * wants_wrap
print("Quantity:", quantity)
print("Gift wrap:", wants_wrap)
print(f"Total: {total:.2f} USD")
assert quantity == 2
assert wants_wrap is False
assert math.isclose(total, 259.98)
Output
Quantity: 2
Gift wrap: False
Total: 259.98 USD

How it works:

  1. Bug 1: " 2 " * 129.99 raises TypeError: can't multiply sequence by non-int of type 'float'. int(" 2 ") returns 2, because int() ignores spaces around the digits.
  2. Bug 2: bool() tests only whether a string is empty. Every non-empty answer, "no" too, gives True. gift_wrap_text == "yes" reads the actual answer.
  3. wrap_fee * wants_wrap is 4.99 * False, which is 0.0. So the total is 2 × 129.99 = 259.98.
  4. The asserts check each fix separately, so a failure points at the broken step.

Alternative: the fix for bug 2 is still fragile: "Yes" or "yes " would count as “no”. Module 02 cleans text with .strip().lower() first: gift_wrap_text.strip().lower() == "yes".