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:
- Read the task and the expected output.
- Copy the starter code into a script (for example
exercise.py) and replace each to-do comment with your code. - Run the script with
python exercise.py. Compare your output with the expected output. - 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
Section titled “Warm-up”M01-W01 · Print a status line
Section titled “M01-W01 · Print a status line”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.
Sensor S1 onlineInterval: 10 minutesStatus: oksensor_id = "S1"interval_minutes = 10status = "ok"# TODO: build line_1, line_2 and line_3 with f-strings# TODO: print the three linesHint 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 = 10status = "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"Sensor S1 onlineInterval: 10 minutesStatus: okHow it works:
- Three assignments give names to the three values.
- Each f-string replaces the name in curly braces with its value. The
int10 becomes the text10. - 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 = 10status = "ok"print("Sensor", sensor_id, "online")print("Interval:", interval_minutes, "minutes")print("Status:", status)Sensor S1 onlineInterval: 10 minutesStatus: okM01-W02 · Check the type of each field
Section titled “M01-W02 · Check the type of each field”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.
product_id <class 'str'>unit_price <class 'float'>sales_lines <class 'int'>in_stock <class 'bool'>discontinued_on <class 'NoneType'>product_id = "P001"unit_price = 79.99sales_lines = 1375in_stock = Truediscontinued_on = None# TODO: print each name and its typeHint 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.99sales_lines = 1375in_stock = Truediscontinued_on = Noneprint("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 floatassert type(sales_lines) is intassert discontinued_on is Noneproduct_id <class 'str'>unit_price <class 'float'>sales_lines <class 'int'>in_stock <class 'bool'>discontinued_on <class 'NoneType'>How it works:
- Quotes make
"P001"astr. 79.99has a decimal point, so it is afloat.1375has none, so it is anint.Trueis abool.Noneis the only value of the typeNoneType.- The asserts use
isto 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.
M01-W03 · Convert units
Section titled “M01-W03 · Convert units”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.
21.5 °C is 70.7 °Fcelsius = 21.5# TODO: convert to Fahrenheit and print the sentenceHint 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.5fahrenheit = celsius * 9 / 5 + 32print(f"{celsius} °C is {fahrenheit:.1f} °F")assert round(fahrenheit, 1) == 70.721.5 °C is 70.7 °FHow it works:
celsius * 9is 193.5. Dividing by 5 gives 38.7. Adding 32 gives 70.7.*and/run before+, so no parentheses are needed.:.1fformats 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.
M01-W04 · Predict the output: division
Section titled “M01-W04 · Predict the output: division”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.
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 itHint 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 == 23assert -23 // 4 == -65.75536.081-6How it works:
23 / 4is the exact quotient, 5.75.23 // 4is 5: four fits into 23 five whole times.23 % 4is 3, the remainder: 23 − 5 × 4 = 3.24 / 4is6.0, not6./gives a float even when the division is exact.3 ** 4is 3 × 3 × 3 × 3 = 81.-23 / 4is −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.
M01-W05 · Text to number
Section titled “M01-W05 · Text to number”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).
Revenue: 109986.25units_text = "1375"price_text = "79.99"# TODO: convert both values and print the revenueHint 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 * priceprint("Revenue:", revenue)assert type(units) is intassert type(revenue) is floatassert round(revenue, 2) == 109986.25Revenue: 109986.25How it works:
int("1375")reads the digits and returns the integer 1375.float("79.99")returns the float 79.99.- An
inttimes afloatgives afloat.
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”Fix the bug: this code should print a label and a count, but it crashes.
units_sold = 1375print("Units sold: " + units_sold)TypeError: can only concatenate str (not "int") to strChange the second line so that it prints:
Units sold: 1375units_sold = 1375print("Units sold: " + units_sold) # TODO: fix this lineHint 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 = 1375print("Units sold: " + str(units_sold))assert str(units_sold) == "1375"Units sold: 1375How it works:
- With a string on the left,
+means “join two strings”. The right side is anint, so Python raises aTypeError. 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”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.
print(bool(0), bool(0.0), bool(""), bool(" "), bool("0"), bool(None), bool(-1.5))# TODO: predict the seven values before you run the lineHint 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 Trueassert bool(-1.5) is TrueFalse False False True True False TrueHow it works:
0and0.0are zero, so they are falsy.""is the empty string, so it is falsy." "holds one space and"0"holds one digit. Neither is empty, so both are truthy.Noneis falsy.- Every number except zero is truthy, negative numbers too.
Alternative: test one value at a time in the REPL, for example >>> bool(" ").
M01-W08 · Refactor: names and comments
Section titled “M01-W08 · Refactor: names and comments”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.
Chicago (S01) is 1430 m² larger than Detroit (S03).a = 2850b = 1420c = a - bprint(c)# TODO: use clear names, add a comment and print the full sentenceHint 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 = 2850detroit_size_sqm = 1420difference_sqm = chicago_size_sqm - detroit_size_sqmprint(f"Chicago (S01) is {difference_sqm} m² larger than Detroit (S03).")assert difference_sqm == 1430Chicago (S01) is 1430 m² larger than Detroit (S03).How it works:
- Each name says what the number is and gives its unit (
_sqm). - The comment gives the source and the unit, which the code cannot show.
- 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.
M01-C01 · Average of three readings
Section titled “M01-C01 · Average of three readings”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.
Average of 3 readings: 21.43 °Cline_1 = "21.0"line_2 = "21.9"line_3 = "21.4"# TODO: convert, average and printHint 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 = 3average = (reading_1 + reading_2 + reading_3) / countprint(f"Average of {count} readings: {average:.2f} °C")assert math.isclose(average, 21.433333333333334)Average of 3 readings: 21.43 °CHow it works:
float()turns each line of text into a number.- The parentheses make Python add before it divides.
- The count is a variable, so the f-string and the formula use the same number.
- 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”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:
Average: 22.47 °Cr1 = 22.0r2 = 22.5r3 = 22.9average = r1 + r2 + r3 / 3 # TODO: fix this formulaprint(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.0r2 = 22.5r3 = 22.9average = (r1 + r2 + r3) / 3print(f"Average: {average:.2f} °C")assert min(r1, r2, r3) <= average <= max(r1, r2, r3)Average: 22.47 °CHow it works:
- The buggy line computes
22.0 + 22.5 + (22.9 / 3), which is 52.13. - The parentheses make Python add the three readings first (67.4), then divide by 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.
M01-C03 · Order revenue with a discount
Section titled “M01-C03 · Order revenue with a discount”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.
Gross: 698.00 USDDiscount: 69.80 USDRevenue: 628.20 USDquantity = 2unit_price = 349.00discount = 0.1# TODO: compute gross, discount amount and revenue, then print themHint 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 = 2unit_price = 349.00discount = 0.1gross = quantity * unit_pricediscount_amount = gross * discountrevenue = gross - discount_amountprint(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)Gross: 698.00 USDDiscount: 69.80 USDRevenue: 628.20 USDHow it works:
grossis 2 × 349.0 = 698.0.discount_amountis 698.0 × 0.1 = 69.8.revenueis 698.0 − 69.8 = 628.2.- 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.
M01-C04 · Pack units into boxes
Section titled “M01-C04 · Pack units into boxes”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).
Full boxes: 47Units left over: 1Boxes to ship: 48units = 1129box_size = 24# TODO: compute full boxes, leftover units and boxes to shipHint 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 = 1129box_size = 24full_boxes = units // box_sizeleft_over = units % box_sizeboxes_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 == unitsassert boxes_to_ship == 48Full boxes: 47Units left over: 1Boxes to ship: 48How it works:
1129 // 24is 47 full boxes (47 × 24 = 1128).1129 % 24is the 1 unit that remains.left_over > 0isTrue. In arithmetic,Truecounts as 1, soboxes_to_shipis 48.- 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 = 1129box_size = 24print("Boxes to ship:", (units + box_size - 1) // box_size)Boxes to ship: 48M01-C05 · Predict the output: strings and numbers
Section titled “M01-C05 · Predict the output: strings and numbers”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.
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 codeHint 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.0343333712.034.0----------How it works:
"3" + "4"joins two strings into"34"."3" * 4repeats the string 4 times.- After
int(),+adds: 3 + 4 = 7. float("3")is 3.0, and 3.0 × 4 is12.0, a float.str(3)is"3"andstr(4.0)is"4.0". Joined, they make"34.0"."-" * 10repeats 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.
M01-C06 · Fix the bug: input is text
Section titled “M01-C06 · Fix the bug: input is text”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 4unit_price = 34.99total = quantity_text * unit_priceprint(total)TypeError: can't multiply sequence by non-int of type 'float'Fix it so that it prints:
Total for 4 yoga mats: 139.96 USDquantity_text = "4" # what input() returns when the clerk types 4unit_price = 34.99total = quantity_text * unit_price # TODO: fix the bugprint(total) # TODO: print the full sentenceHint 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 4unit_price = 34.99quantity = int(quantity_text)total = quantity * unit_priceprint(f"Total for {quantity} yoga mats: {total:.2f} USD")assert type(quantity) is intassert math.isclose(total, 139.96)Total for 4 yoga mats: 139.96 USDHow it works:
input()always returns astr, soquantity_textis"4".- A string times an
intrepeats the string. A string times afloathas no meaning, so Python raises aTypeError. 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.
M01-C07 · Flag out-of-range readings
Section titled “M01-C07 · Flag out-of-range readings”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.
21.7 in range: True18.4 in range: False23.0 in range: True25.1 in range: Falselow = 19.0high = 23.0reading_a = 21.7reading_b = 18.4reading_c = 23.0reading_d = 25.1# TODO: print each reading and whether it is in rangeHint 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.0high = 23.0reading_a = 21.7reading_b = 18.4reading_c = 23.0reading_d = 25.1print(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 Trueassert (low <= reading_d <= high) is False21.7 in range: True18.4 in range: False23.0 in range: True25.1 in range: FalseHow it works:
low <= reading_a <= highmeanslow <= reading_a and reading_a <= high.- 23.0 is exactly the upper limit. With
<=, it is valid. - 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.
M01-C08 · Churn risk rule
Section titled “M01-C08 · Churn risk rule”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.
Month-to-month: FalseMany tickets: FalseNo autopay: TrueHigh risk: Falsecontract = "one-year"support_tickets = 1has_autopay = 0# TODO: build the three flags and combine themHint 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 = 1has_autopay = 0is_monthly = contract == "month-to-month"many_tickets = support_tickets >= 3no_autopay = has_autopay == 0high_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 Falseassert (is_monthly and many_tickets or no_autopay) is True # the version without ()Month-to-month: FalseMany tickets: FalseNo autopay: TrueHigh risk: FalseHow it works:
- Each comparison gives one
boolwith a clear name. - The parentheses group the two alternatives. A one-year contract fails the first part, so the customer is not high risk.
- The last assert shows the bug you avoid: without parentheses, Python reads
(is_monthly and many_tickets) or no_autopay, which isTruefor 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”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?
TrueFalseFalse<class 'NoneType'>discount = Noneprint(discount is None)print(discount == 0)print(bool(discount))print(type(discount))# TODO: explain each result; then set discount = 0.0 and run againHint 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 = Noneprint(discount is None)print(discount == 0)print(bool(discount))print(type(discount))assert (discount is None, discount == 0, bool(discount)) == (True, False, False)TrueFalseFalse<class 'NoneType'>Now the same lines with a real discount of zero:
discount = 0.0print(discount is None)print(discount == 0)print(bool(discount))print(type(discount))assert (discount is None, discount == 0, bool(discount)) == (False, True, False)FalseTrueFalse<class 'float'>How it works:
discount is NoneisTrueonly forNone. It is the correct test for a missing value.discount == 0isFalseforNone, becauseNoneis not a number. It isTruefor0.0.bool(discount)isFalsefor both. Both values are falsy, sobool()cannot tell “missing” from “zero”.type()showsNoneTypefor the missing value andfloatfor 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”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.
Total: 94.97999999999999== invoice: Falserounded == invoice: Trueisclose: Trueimport math
earbuds = 79.99socks = 14.99invoice = 94.98total = earbuds + socks# TODO: print the total, then the result of ==, of round(total, 2) == and of math.iscloseHint 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.99socks = 14.99invoice = 94.98total = earbuds + socksprint("Total:", total)print("== invoice:", total == invoice)print("rounded == invoice:", round(total, 2) == invoice)print("isclose:", math.isclose(total, invoice))assert math.isclose(total, invoice)Total: 94.97999999999999== invoice: Falserounded == invoice: Trueisclose: TrueHow it works:
- The binary forms of 79.99 and 14.99 are not exact, so their sum is a hair below 94.98.
==compares every bit and reportsFalse, although the money is correct.- Rounding to cents removes the error, so the rounded value equals the invoice.
math.isclose()accepts a tiny relative difference, so it reportsTrue.
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.
M01-C11 · Format a receipt
Section titled “M01-C11 · Format a receipt”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.
Store S07 (New York)Order date: 2024-05-013 x Non-Slip Yoga Mat @ 34.99 = 104.97 USD--------------------------store_id = "S07"city = "New York"product = "Non-Slip Yoga Mat"quantity = 3unit_price = 34.99# TODO: print the four linesHint 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 = 3unit_price = 34.99line_total = quantity * unit_priceprint(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.97Store S07 (New York)Order date: 2024-05-013 x Non-Slip Yoga Mat @ 34.99 = 104.97 USD--------------------------How it works:
- The f-string puts the store id and the city into the first line.
end=""replaces the line break after"Order date: "with nothing, so the nextprint()continues the same line.sep="-"puts a dash between the three date parts instead of a space.:.2fshows both amounts with exactly 2 decimals, which hides the float error inline_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.
M01-C12 · Choose int(), round() or //
Section titled “M01-C12 · Choose int(), round() or //”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?
Display temperature: 22Full hours: 2Completed years: 42temperature = 21.7session_minutes = 135age_years = 42.9# TODO: pick round(), int() or // for each value and print itHint 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.7session_minutes = 135age_years = 42.9display_temperature = round(temperature)full_hours = session_minutes // 60completed_years = int(age_years)print("Display temperature:", display_temperature)print("Full hours:", full_hours)print("Completed years:", completed_years)assert display_temperature == 22assert full_hours == 2assert completed_years == 42Display temperature: 22Full hours: 2Completed years: 42How it works:
- 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. - Hours: you count complete units of 60 minutes, so
//is the natural tool. It also keeps the value anint. - 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.
Challenge
Section titled “Challenge”M01-X01 · Summarize a batch of raw readings
Section titled “M01-X01 · Summarize a batch of raw readings”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.
Readings: 5Min: 21.0 °CMax: 22.1 °CRange: 1.1 °CMean: 21.62 °C (70.92 °F)Drift first to last: +1.1 °CAll in range 19.0-23.0 °C: Trueraw_1 = "21.0"raw_2 = "21.9"raw_3 = "21.4"raw_4 = "21.7"raw_5 = "22.1\n"low_limit = 19.0high_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 reportHint 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.0high_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 breakcount = 5
lowest = min(r1, r2, r3, r4, r5)highest = max(r1, r2, r3, r4, r5)spread = highest - lowestmean_c = (r1 + r2 + r3 + r4 + r5) / countmean_f = mean_c * 9 / 5 + 32drift = r5 - r1 # positive: the room got warmerall_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 <= highestassert math.isclose(mean_c, 21.62)assert math.isclose(spread, 1.1)assert all_in_range is TrueReadings: 5Min: 21.0 °CMax: 22.1 °CRange: 1.1 °CMean: 21.62 °C (70.92 °F)Drift first to last: +1.1 °CAll in range 19.0-23.0 °C: TrueHow it works:
float()converts each line. It strips the\nof the last line for you.min()andmax()return the smallest and largest of their arguments. The range is their difference.- 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.
- The drift compares the last reading with the first. The format spec
:+.1fshows+1.1, so a reader sees the direction at once. - 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.
- 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”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.
Readings per day: 144Reading number for 2024-05-09 15:20: 1244Check: reading 1244 is at 2024-05-09 15:20interval_minutes = 10day_of_month = 9hour = 15minute = 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 checkHint 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 = 10day_of_month = 9hour = 15minute = 20
# Forward: clock time -> reading number.readings_per_day = 24 * 60 // interval_minutesfull_days = day_of_month - 1minutes_since_midnight = hour * 60 + minutereading_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_dayminutes_back = reading_number % readings_per_day * interval_minuteshour_back = minutes_back // 60minute_back = minutes_back % 60print( f"Check: reading {reading_number} is at " f"2024-05-{1 + days_back:02d} {hour_back:02d}:{minute_back:02d}")
assert readings_per_day == 144assert reading_number == 1244assert (1 + days_back, hour_back, minute_back) == (day_of_month, hour, minute)Readings per day: 144Reading number for 2024-05-09 15:20: 1244Check: reading 1244 is at 2024-05-09 15:20How it works:
24 * 60 // 10is 144 readings per day.*and//have the same precedence and run left to right.- May 9 is 8 full days after May 1: 8 × 144 = 1152 readings.
- 15:20 is 920 minutes after midnight, which is 92 readings. 1152 + 92 = 1244.
- Going back,
1244 // 144is 8 full days and1244 % 144is 92 readings, which is 920 minutes. 920 // 60is 15 hours and920 % 60is 20 minutes.- Parentheses around a long expression let it continue on the next line. Two f-strings next to each other join into one string.
- 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”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.
Product: 55-inch 4K Smart TV (P003)Unit cost: 845.00 USDList price: 1299.00 USDMargin at list price: 454.00 USD per unit (34.9%)Order line: 2 units at 20% discountDiscounted price: 1039.20 USDLine revenue: 2078.40 USDLine margin: 388.40 USD (18.7%)Margin rate below 30%: Truea=845.0b=1299.0c=b-ad=c/b*100print(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, flagHint 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 supplierunit_price = 1299.00 # list price: what the customer pays without a discountmin_margin_rate = 0.30 # finance team's minimum, as a fraction of the selling price
# Margin at list price.list_margin = unit_price - unit_costlist_margin_rate = list_margin / unit_price
# One discounted sales line, shaped like a line of data/sales.csv.quantity = 2discount = 0.2discounted_price = unit_price * (1 - discount)line_revenue = quantity * discounted_priceline_cost = quantity * unit_costline_margin = line_revenue - line_costline_margin_rate = line_margin / line_revenuebelow_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 numbersassert round(list_margin_rate * 100, 1) == 34.9assert math.isclose(line_margin, 388.4)assert below_minimum is TrueProduct: 55-inch 4K Smart TV (P003)Unit cost: 845.00 USDList price: 1299.00 USDMargin at list price: 454.00 USD per unit (34.9%)Order line: 2 units at 20% discountDiscounted price: 1039.20 USDLine revenue: 2078.40 USDLine margin: 388.40 USD (18.7%)Margin rate below 30%: TrueHow it works:
- 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. - 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.
- Discount. 1299.00 × (1 − 0.2) = 1039.20 per unit. Two units bring 2078.40 in revenue and cost 1690.00.
- Line margin. 2078.40 − 1690.00 = 388.40, which is 18.7% of the line revenue.
- Flag. 0.187 < 0.30, so
below_minimumisTrue. A 20% discount cuts the margin by more than half, because the discount comes out of the margin only: the cost stays the same. - 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”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.
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: Trues01_lines = 2220s01_size_sqm = 2850s01_days_open = 731s12_lines = 868s12_size_sqm = 1350s12_days_open = 566# TODO: compute lines per day per 1,000 m² for both stores# TODO: print both rates and compare themHint 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 = 2220s01_size_sqm = 2850s01_days_open = 731s12_lines = 868s12_size_sqm = 1350s12_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 Chicagoassert s12_rate > s01_rate # the fair rate favors DenverS01 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: TrueHow it works:
- Dividing by the days open removes the effect of S12’s late opening.
- Dividing by the size in thousands of m² removes the effect of Chicago’s larger floor.
- The parentheses around
size_sqm / 1000make Python compute the size first. Without them,lines / days / size * 1000would also work, but the version with parentheses reads like the definition. - 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.
M01-X05 · Fix the bugs: parse a web form
Section titled “M01-X05 · Fix the bugs: parse a web form”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:
Quantity: 2Gift wrap: FalseTotal: 259.98 USDquantity_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 1unit_price = float(price_text)wants_wrap = bool(gift_wrap_text) # TODO: bug 2total = quantity * unit_price + wrap_fee * wants_wrapprint("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 numberunit_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_wrapprint("Quantity:", quantity)print("Gift wrap:", wants_wrap)print(f"Total: {total:.2f} USD")
assert quantity == 2assert wants_wrap is Falseassert math.isclose(total, 259.98)Quantity: 2Gift wrap: FalseTotal: 259.98 USDHow it works:
- Bug 1:
" 2 " * 129.99raisesTypeError: can't multiply sequence by non-int of type 'float'.int(" 2 ")returns 2, becauseint()ignores spaces around the digits. - Bug 2:
bool()tests only whether a string is empty. Every non-empty answer,"no"too, givesTrue.gift_wrap_text == "yes"reads the actual answer. wrap_fee * wants_wrapis4.99 * False, which is0.0. So the total is 2 × 129.99 = 259.98.- 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".