Chapter 0: Basics of Python
About This Chapter
This chapter assumes no prior programming experience and is written for a high-school student starting from zero. You only need familiar arithmetic: addition, subtraction, multiplication, and division. We introduce every programming idea before using it in a larger example.
Python is a language for giving instructions to a computer. Here it runs inside your browser. You do not need to install Python, understand a command line, or already know business terminology. We begin with greetings, pocket money, tickets, and scores, then explain the vocabulary in the shop and savings examples.
Chapter 1–4 are designed for second-year business-school students. This chapter supplies their programming foundation. Do not rush: predicting an output and explaining why it appears is more useful than copying code you cannot yet read.
What This Chapter Covers
No programming background is needed. We start with familiar school and everyday examples.
- Values and variables — names,
int, andfloat - Calculations — arithmetic and the order of operations
- Text —
str, conversion, and f-strings - Decisions — comparisons, Boolean logic, and
if - Lists and repetition — list methods,
for, and condition-controlledwhileloops - Functions — give inputs, get a result
Chapter 1–4 build on these basics for second-year business-school students.
How to Learn with These Slides
For each example:
- Read the short explanation and predict the result.
- Run the code after Python finishes loading.
- Change one thing and run it again.
- Check the output against a hand calculation.
Practice cells wait for you to click Run. Edit the code, not the output. These examples run in the browser; no Python installation is needed.
The Chapter 0 book follows the same examples with extra explanations.
Values, Variables, and Calculations
Your First Line
Python is a programming language: we write instructions, and Python follows them.
print(...) means show this on the screen. The parentheses hold what we want to show. Matching quotes mark text.
Expected output: Hello, Python! — without the quotation marks. Change the message to your own greeting.
Printing Text and Calculations
Numbers do not need quotes. Text does. Python calculates the expression before print() displays it.
The outputs are 2 + 3, 5, and Answer: 5.
The comma lets print() show more than one value, separated by a space. Try replacing 3 with 8.
Variables: Give a Value a Name
A variable is a name that refers to a value. A useful name tells us what the value means.
Read pocket_money = 100 as: make the name pocket_money refer to 100. = is assignment, not an equation to solve.
Python first calculates the right side of =, then assigns the result to the name on the left. The output is 75.
Names are case-sensitive: price and Price are different. Use names such as snack_cost; do not start a name with a digit.
Reassignment: Update a Value
A name can be assigned again. The new value replaces what the name previously referred to.
Outputs: 10, then 15. In the update, Python reads the old 10, adds 5, and assigns 15.
points = points + 5 makes sense as an instruction, even though it would not make sense as an algebraic equation.
Calculations Do Not Update Themselves
A calculated value remembers the result of that calculation. It does not automatically recalculate when an input changes.
Outputs: 20, then 24. We must run the calculation again to use the new price. Rerunning this whole cell starts again at price = 10.
Practice: Update Your Pocket Money
Start with HK$100, receive HK$20, then spend HK$35. Finish the two updates.
Expected result: Money left: 85. Then start with 50 instead of 100; the result should be 35.
Types: What Kind of Value Is This?
A type tells Python what kind of value it is working with. The value has the type; the variable name can be reassigned.
| Python name | Meaning | Example |
|---|---|---|
int |
Integer: a whole number | 4 |
float |
An approximate decimal number | 12.5 |
str |
String: text | "hello" |
type(value) asks Python to tell us the type.
Outputs include <class 'int'>, <class 'float'>, and <class 'str'>. Read these as “integer”, “float”, and “string”. We will practise each type separately.
int: Whole Numbers
int is short for integer. Integers include positive whole numbers, zero, and negative whole numbers. Use them for counts such as students or tickets.
Outputs: 28, the type int, then 1000 1000.
An underscore makes a large number easier to read: 1_000 and 1000 have the same value. Use it instead of a thousands comma in a number literal.
float: Numbers with a Decimal Point
A float represents an approximate number, often written with a decimal point. Use examples such as prices, lengths, and rates.
Outputs start with 12.5 and 50.0. Python need not display trailing zeros.
4 is an int; 4.0 is a float. A float can represent a whole-number value too. Here multiplying an int by a float produces a float.
Floats cannot represent every decimal fraction exactly. This is a storage detail, not a mistake in your typing. For now, focus on choosing the correct kind of value; an optional precision example appears later.
Addition and Subtraction: + and -
+ adds two numbers. - subtracts the second number from the first. A leading minus sign makes a number negative.
Expected outputs: 9, 5, -5, 3.5, -2.
Predict 10 - 4 + 2, then add a line to check it. Addition and subtraction at this level are evaluated from left to right.
Multiplication and Division: * and /
Use * for multiplication and / for division. Python does not use the written symbols × and ÷ as operators.
Outputs: 14, 3.5, 4.0, and the type float.
Dividing these built-in numeric types with / produces a float, even when the answer is a whole number. Dividing by zero raises ZeroDivisionError.
Powers: Use ** for Exponents
A power means repeated multiplication for a positive whole-number exponent.
2 ** 3 means 2 × 2 × 2. The first number is the base; the second is the exponent.
Outputs: 8, 8, 25, 1.
Use two asterisks together: **. The symbol ^ is a different Python operator and does not mean power. Try 3 ** 2 and 2 ** 3: do they give the same result?
Floor Division and Remainders: // and %
Suppose 7 biscuits are shared into groups of 2. We can make 3 complete groups, with 1 biscuit left.
Outputs: 3.5, 3, 1, 7.
For nonnegative whole-number counts, // gives the number of complete groups and % gives the remainder. More generally, // takes the floor: -7 // 2 is −4, not −3. Here % is not a percentage sign.
Order of Operations and Parentheses
Python uses the usual arithmetic order: powers, then multiplication/division, then addition/subtraction. Parentheses ask Python to do a group first.
Outputs: 14, 20, 18, 36. Write out the steps on paper.
Use parentheses when they make your intended calculation clearer. These examples use positive bases; write (-3) ** 2 when the negative sign belongs to the base.
Practice: Pack Items into Boxes
There are 23 items. Each box holds 5. Use // and % to calculate the number of full boxes and the items left.
Expected: 4 full boxes, 3 items left, and 23 accounted for. Test 25 items: 5 full boxes, 0 left. Test fewer items than one box can hold.
Section 1 — Practice: Values and Calculations
Work from question 1 to 10. Write your code, click Run Code, review the result, then click Submit attempt. An attempt may be wrong: reference answers become available after you submit all 10. Each Python box is independent. Submission progress is saved in this browser.
1. Show a greeting
Warm-up. Print the message Hello, Python! Use matching quotes.
Write your answer, then run it.
2. Text or a calculation?
Warm-up. Print the text 4 + 6, then print the result of adding 4 and 6. Use two lines.
Write your answer, then run it.
3. Money left
Warm-up. You have HK$80 and spend HK$18. Create money_left and print it.
Write your answer, then run it.
4. Update a score
Build your skills. Start with 12 points. Add 8, then subtract 3, reassigning points each time. Print the final value.
Write your answer, then run it.
5. Inspect numeric types
Build your skills. Print the type of quantity, the type of price, and the result of quantity * price.
Write your answer, then run it.
6. Divide in three ways
Build your skills. Print 17 / 5, 17 // 5, and 17 % 5, each on its own line.
Write your answer, then run it.
7. Use parentheses
Build your skills. Write two calculations: add 3 and 5, then multiply the result by 2; multiply 5 by 2, then add 3. Print both.
Write your answer, then run it.
8. Square and cube
Challenge. The side of a square is 6 cm. Print its area using a power. A cube has side 3 cm; print its volume using a power.
Write your answer, then run it.
9. Pack a delivery
Challenge. There are 38 pencils and each box holds 6. Print full boxes, pencils left, and the number accounted for. Use // and %.
Write your answer, then run it.
10. A small shopping budget
Challenge. You have HK$100. Buy 2 notebooks at HK$15 each and 3 pens at HK$4 each. Calculate total_spent and money_left, then print both. Define the inputs yourself.
Write your answer, then run it.
Reference answers are locked until all 10 attempts are submitted.
1. Show a greeting
print("Hello, Python!")Expected output
Hello, Python!Quotes create text; print displays it without the quotes.
2. Text or a calculation?
print("4 + 6")
print(4 + 6)Expected output
4 + 6
10The quoted expression is text; the unquoted expression is evaluated.
3. Money left
money = 80
snack_cost = 18
money_left = money - snack_cost
print(money_left)Expected output
62Subtract spending from the starting amount.
4. Update a score
points = 12
points = points + 8
points = points - 3
print(points)Expected output
17Each update reads the previous value and assigns the new one.
5. Inspect numeric types
quantity = 3
price = 2.5
print(type(quantity))
print(type(price))
print(quantity * price)Expected output
<class 'int'>
<class 'float'>
7.5An integer count times this float price produces a float.
6. Divide in three ways
print(17 / 5)
print(17 // 5)
print(17 % 5)Expected output
3.4
3
2Division gives 3.4; three complete groups of five use 15 items, leaving two.
7. Use parentheses
print((3 + 5) * 2)
print(3 + 5 * 2)Expected output
16
13Parentheses change which operation happens first.
8. Square and cube
square_side = 6
cube_side = 3
print(square_side ** 2)
print(cube_side ** 3)Expected output
36
27A square uses the second power; a cube uses the third power. Units are cm² and cm³.
9. Pack a delivery
pencils = 38
capacity = 6
full_boxes = pencils // capacity
leftover = pencils % capacity
print(full_boxes)
print(leftover)
print(full_boxes * capacity + leftover)Expected output
6
2
38Six full boxes hold 36 pencils; two remain. Reconstructing the total checks the arithmetic.
10. A small shopping budget
budget = 100
notebook_quantity = 2
notebook_price = 15
pen_quantity = 3
pen_price = 4
total_spent = notebook_quantity * notebook_price + pen_quantity * pen_price
money_left = budget - total_spent
print(total_spent)
print(money_left)Expected output
42
58The two product costs are 30 and 12. Add them before subtracting from the budget.
Strings and Clear Output
str: A String Is Text
str is short for string: a sequence of characters. Characters can be letters, spaces, digits, or symbols. Matching single or double quotes create text.
The quoted "250" is text even though its characters look like a number. The last line shows str and int. Quotes tell Python how to interpret what you wrote.
The Same + Has Different Jobs
With numbers, + performs addition. With strings, + joins the text, called concatenation.
Outputs: 350, 100250, Hello, Alex, hahaha.
String multiplication by an integer repeats the text. Python does not silently guess how to add a number to a string: 100 + "250" raises TypeError.
f-strings: Put Values into a Message
An f-string is a string with an f just before the opening quote. Put a value or expression inside {...} to insert its result into the text.
Without f: Hello, {name}. With f: Hello, Alex.
The last line prints age 17. An f-string produces text; f is a prefix, not a separate variable you need to define.
Formatting: Two Decimal Places
A format instruction follows a colon inside the braces. :.2f means display a number with two digits after the decimal point.
Outputs: Price: HK$12.50, the type str, then 12.5 and float.
Formatting creates a readable message. It does not change the value or type of price. Try price = 12.567: the label displays HK$12.57 while the stored value remains 12.567.
Convert Text Before Doing Arithmetic
Text from a form can look numeric. Conversion creates a value of a different type: use int() for whole-number text and float() for decimal text.
Outputs: 50.0 and 250 dollars. str() converts a value to text.
Choose the conversion to match the data: int("12.50") fails; float("12.50") works. int(3.9) gives 3, because it truncates toward zero rather than rounding.
Practice: Convert Text into Numbers
A form returns the price and quantity as text. Convert the price with float() and the quantity with int(), then calculate the bill.
Expected types: float, int. Expected bill: HK$50.00. Then change the inputs to "18.75" and "3"; the bill should be HK$56.25.
Strings: Working with Text
A method is an operation called after a value with a dot. name.upper() means “make an uppercase version of this text”. Parentheses call the method.
.strip() removes surrounding spaces; .upper() changes letter case. The combined result is HKUST CAFE.
These methods return new text. The original name still has its spaces and lowercase letters. .lower() makes a lowercase version.
Practice: Clean a Company Label
Edit clean_name to remove surrounding spaces and convert the name to uppercase. Try a second input with different spaces and case.
Use .strip() and .upper(). Expected output: Clean label: [HKUST CAFE], with no spaces next to the brackets. Test different surrounding spaces too.
A Shop Calculation: Revenue, Cost, Profit
Revenue is money from sales. Cost is money spent in this example. Profit = revenue − cost. Margin = profit ÷ revenue.
Profit is HK$370,000; margin is 29.6%. :, displays thousands commas. :.1% displays a fraction as a percentage with one decimal place.
We have not specified which expenses cost includes. The example does not establish a real company’s gross or net margin.
Section 2 — Practice: Strings and Output
Work from question 1 to 10. Write your code, click Run Code, review the result, then click Submit attempt. An attempt may be wrong: reference answers become available after you submit all 10. Each Python box is independent. Submission progress is saved in this browser.
1. Create a string
Warm-up. Store your example name Alex in a variable and print it. Print its type on a second line.
Write your answer, then run it.
2. Join two names
Warm-up. Join first_name and last_name with a space between them. Print the full name.
Write your answer, then run it.
3. Repeat text
Warm-up. Use string multiplication to print Go! three times, with spaces between the words.
Write your answer, then run it.
4. A birthday message
Build your skills. Using an f-string, print Next year Alex will be 17. Calculate the next age inside the braces.
Write your answer, then run it.
5. Display a price
Build your skills. Print Price: HK$8.50 using an f-string and two decimal places. Then print the stored price itself.
Write your answer, then run it.
6. Numeric text
Build your skills. Convert the text values to integers and print their numeric sum. Do not join the text.
Write your answer, then run it.
7. A bill from form inputs
Build your skills. Convert the price text to float and quantity text to int. Print Bill: HK$37.50.
Write your answer, then run it.
8. Clean a label
Challenge. Remove the surrounding spaces and convert the label to uppercase. Print the clean label between square brackets so extra spaces are visible.
Write your answer, then run it.
9. Keep an identifier as text
Challenge. The student identifier is 0042. Keep its leading zeros. Print Student: 0042; on a second line show what int(student_id) would produce.
Write your answer, then run it.
10. A complete receipt
Challenge. Clean the item name, convert the numeric text, and print PEN: 3 items, HK$13.50 using an f-string.
Write your answer, then run it.
Reference answers are locked until all 10 attempts are submitted.
1. Create a string
name = "Alex"
print(name)
print(type(name))Expected output
Alex
<class 'str'>A name inside quotes is text, of type str.
2. Join two names
first_name = "Alex"
last_name = "Chan"
full_name = first_name + " " + last_name
print(full_name)Expected output
Alex ChanConcatenation does not insert a space automatically; include the space as text.
3. Repeat text
print("Go! " * 3)Expected output
Go! Go! Go! The repeated string includes a space. A trailing space is harmless here.
4. A birthday message
name = "Alex"
age = 16
print(f"Next year {name} will be {age + 1}.")Expected output
Next year Alex will be 17.The f prefix evaluates the expressions inside braces.
5. Display a price
price = 8.5
print(f"Price: HK${price:.2f}")
print(price)Expected output
Price: HK$8.50
8.5Formatting produces a label without changing the stored number.
6. Numeric text
first_text = "20"
second_text = "5"
print(int(first_text) + int(second_text))Expected output
25Without conversion, joining these strings would give 205.
7. A bill from form inputs
price_text = "12.50"
quantity_text = "3"
price = float(price_text)
quantity = int(quantity_text)
subtotal = price * quantity
print(f"Bill: HK${subtotal:.2f}")Expected output
Bill: HK$37.50Choose conversions that match a decimal price and a whole-number count.
8. Clean a label
raw_label = " school cafe "
clean_label = raw_label.strip().upper()
print(f"[{clean_label}]")Expected output
[SCHOOL CAFE]strip and upper return new strings; the brackets make surrounding spaces easy to check.
9. Keep an identifier as text
student_id = "0042"
print(f"Student: {student_id}")
print(int(student_id))Expected output
Student: 0042
42An identifier is often text. Numeric conversion loses its display-leading zeros.
10. A complete receipt
item_text = " pen "
quantity_text = "3"
price_text = "4.50"
item = item_text.strip().upper()
quantity = int(quantity_text)
price = float(price_text)
bill = quantity * price
print(f"{item}: {quantity} items, HK${bill:.2f}")Expected output
PEN: 3 items, HK$13.50Text cleaning, numeric conversion, calculation, and formatting serve different purposes.
Comparisons and Decisions
Comparisons Give True or False
A comparison asks a yes/no question. Its answer has type bool, short for Boolean: True or False, with capitals and no quotes.
Outputs: False, True, True, False, then bool.
> means greater than; >= means greater than or equal; == means equal; != means not equal. Similarly, < means less than and <= includes equality.
Assignment = versus Comparison ==
= gives a name a value. == asks whether two values are equal. They do different jobs.
Outputs: 70, True, True, False. An int and a float can compare numerically equal. The text "4" and the integer 4 are different values.
Do not put quotes around Boolean values: "False" is text, not the Boolean False.
Boolean Logic: True or False?
Use and when both conditions must hold. Use or when at least one must hold. not reverses a Boolean result.
Outputs: False, True, True.
Change has_student_card to True and predict all three results before running again. We use Boolean inputs here; these examples are yes/no decisions.
Practice: Combine Two Conditions
Approve a classroom screen only if price > 50 AND volume > 1,000,000. Define both comparisons and combine them. Then change volume to 5,000,000.
With the first inputs, the three results are True, False, False. After increasing volume, all three should be True.
Practice: Reach a Profit Target
Set cost so that profit exceeds HK$420,000. Find the exact boundary first: does cost = 830,000 pass?
The condition is strict: cost must be below 830,000.
Start with One if / else Decision
if runs its indented instructions when a condition is true. else runs its instructions otherwise. The colon : starts a block.
At 65 the output is Pass, then Check finished. Try 59 and exactly 60.
These are classroom thresholds. The last line is not indented, so it runs after either branch.
Indentation Shows Which Lines Belong Together
Indentation means spaces at the start of a line. Use four spaces for instructions inside a block. Lines aligned at the same level belong to that level.
At False, only Leave home prints. Change to True: all three messages print.
The first two messages belong to if; the last does not. Missing indentation after a block header raises an indentation error.
If / Elif / Else
Each condition is checked in order; the first true branch runs and the rest are skipped. The else catches everything that wasn’t matched above.
These thresholds are a teaching example, not the course grading policy. If score >= 70 comes first, all scores of 70 or above enter C; 50 still enters F.
Read the trace at score 82: 82 >= 90 is false, so continue; 82 >= 80 is true, so assign B and skip the remaining branches. elif means “else if”. In this chain, at most one branch runs.
Practice: Debug the Branch Order
This code runs, but its overlapping conditions are in the wrong order. Fix the order and test scores 95, 82, 70, and 69.
Expected grades: A, B, C, F. Put the highest threshold first.
Section 3 — Practice: Comparisons and Decisions
Work from question 1 to 10. Write your code, click Run Code, review the result, then click Submit attempt. An attempt may be wrong: reference answers become available after you submit all 10. Each Python box is independent. Submission progress is saved in this browser.
1. At least 18?
Warm-up. Print whether age is at least 18. Use a comparison, not a quoted message.
Write your answer, then run it.
2. Assignment and equality
Warm-up. Assign 60 to score. Print whether score equals 60, then whether it is greater than 60.
Write your answer, then run it.
3. Strict or inclusive?
Warm-up. Print whether money exceeds cost, then whether money is enough to pay cost exactly.
Write your answer, then run it.
4. Both are required
Build your skills. Entry requires a ticket AND a student card. Print whether entry is allowed.
Write your answer, then run it.
5. At least one is enough
Build your skills. A visitor can pay with cash OR a bank card. Print whether they have a way to pay, then whether they lack cash.
Write your answer, then run it.
6. Choose a message
Build your skills. If score is at least 60, print Pass; otherwise print Try again. Also test exactly 60 and 59 yourself.
Write your answer, then run it.
7. Three categories
Build your skills. Print Hot for temperature >= 30, Warm for >= 20, and Cool otherwise. Use if / elif / else.
Write your answer, then run it.
8. Combine tests in a decision
Challenge. Allow a purchase only if money covers cost AND the item is in stock. Print Buy or Wait.
Write your answer, then run it.
9. Repair overlapping branches
Challenge. This order gives the wrong grade at score 95. Fix it: A >= 90, B >= 80, C >= 70, F otherwise. Test 90, 80, 70, and 69 too.
Write your answer, then run it.
10. Choose a ticket price
Challenge. Use the following classroom rules: under 12 pays HK$20; otherwise a student pays HK$30; everyone else pays HK$50. Set ticket_price and print it with two decimal places. Test an 11-year-old nonstudent and a 20-year-old nonstudent too.
Write your answer, then run it.
Reference answers are locked until all 10 attempts are submitted.
1. At least 18?
age = 17
print(age >= 18)Expected output
FalseAt least includes equality, so use >=.
2. Assignment and equality
score = 60
print(score == 60)
print(score > 60)Expected output
True
FalseAssignment uses =; comparison for equality uses ==.
3. Strict or inclusive?
money = 25
cost = 25
print(money > cost)
print(money >= cost)Expected output
False
TrueHaving exactly the cost is enough to pay, but it does not exceed the cost.
4. Both are required
has_ticket = True
has_student_card = False
print(has_ticket and has_student_card)Expected output
Falseand is true only when both Boolean inputs are true.
5. At least one is enough
has_cash = False
has_bank_card = True
print(has_cash or has_bank_card)
print(not has_cash)Expected output
True
Trueor needs at least one true condition; not reverses a Boolean.
6. Choose a message
score = 65
if score >= 60:
print("Pass")
else:
print("Try again")Expected output
PassThe indented line in the matching branch runs.
7. Three categories
temperature = 24
if temperature >= 30:
print("Hot")
elif temperature >= 20:
print("Warm")
else:
print("Cool")Expected output
WarmAt 24 the first test fails and the second is true.
8. Combine tests in a decision
money = 50
cost = 40
in_stock = False
if money >= cost and in_stock:
print("Buy")
else:
print("Wait")Expected output
WaitEnough money alone does not satisfy the stock requirement.
9. Repair overlapping branches
score = 95
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade)Expected output
APut the highest overlapping threshold first. These are teaching grades, not course policy.
10. Choose a ticket price
age = 16
is_student = True
if age < 12:
ticket_price = 20
elif is_student:
ticket_price = 30
else:
ticket_price = 50
print(f"HK${ticket_price:.2f}")Expected output
HK$30.00The under-12 rule has priority; only older visitors reach the student test.
Lists and Repetition
A Small List Holds Several Values
A list keeps several values in order. Use square brackets [...] and commas between items.
Outputs: [70, 80, 90], 3, 240.
len(scores) counts the items. sum(scores) adds these numeric items. Add a fourth score and check both results. Next we learn how to read, change, and search a list before using loops.
Read and Update a List Item
An index is an item’s position. Python starts counting positions at 0, not 1. Square brackets after the list name select an item.
| Item | 70 | 80 | 90 |
|---|---|---|---|
| Index | 0 | 1 | 2 |
Outputs: 70, 90, [70, 85, 90]. Index -1 selects the last item. Assignment to scores[1] replaces the second item; the list length stays three.
For this list, index 3 is outside the list and raises IndexError. Predict the result if you replace the first item with 75.
Add Items: append versus extend
A method is an operation belonging to an object. Read scores.append(90) as “ask the scores list to add 90”. The dot connects the list to its method; parentheses supply the input.
Outputs: [70, 80, 90], then [70, 80, 90, 85, 95]. append adds one item; extend adds each item from another list.
Outputs: [70, 80, [85, 95]], then 3. Here the added item is itself a list. Use extend when you want the two scores as separate items.
Insert an Item at a Position
insert(index, value) puts a new item before the item currently at that index. Existing items move to make room; no item is replaced.
Outputs: [70, 80, 90], then [60, 70, 80, 90]. Index 0 means the front. Compare inserting at index 1 with assigning scores[1] = 80: insertion increases the length, while assignment does not.
Try inserting 95 at the end using index len(scores).
Remove an Item: remove versus pop
remove(value) deletes the first matching value. pop(index) deletes the item at a position and returns the removed value. With no index, pop() takes the last item.
Outputs: [80, 70, 90], Removed: 90, [80, 70], Removed: 80, [70]. The second 70 survives remove(70) because only the first match is removed.
remove raises ValueError if the value is absent. pop raises IndexError if the position is invalid or the list is empty. These methods change the list itself.
Search a List: count and index
count(value) tells us how many matches there are. index(value) gives the position of the first match. value in scores tests whether the value is present and gives True or False.
Outputs: 2, 0, 0, False, Position of 90: 3. Zero matches is a valid count. An absent value has no index: index(100) would raise ValueError.
The final if checks membership before looking up the position. Change the searched value to 100 and observe that the indented print is skipped.
Change the Order: sort and reverse
sort() puts comparable items in ascending order. reverse() flips the current order; it does not sort the items first.
Outputs: Reversed: [70, 90, 60, 80], Ascending: [60, 70, 80, 90], Descending: [90, 80, 70, 60].
These methods change the existing list and return None, meaning no result value. Use scores.sort() followed by print(scores); assigning scores = scores.sort() would make the name refer to None.
Keep a Copy and Clear a List
copy() makes a new outer list. For our lists of numbers, changing one copy’s items does not change the other. In contrast, alias = scores gives the same list another name.
Outputs: Scores: [70, 80, 90], Alias: [70, 80, 90], Backup: [70, 80], Cleared backup: [], Scores still: [70, 80, 90].
clear() removes all items from that list. Copying a list containing other lists is a shallow copy: its inner lists are still shared. We use simple number lists here.
List Methods: Choose the Operation
| Method | What it does |
|---|---|
append(value) |
Add one item at the end |
extend(values) |
Add the individual items from another list |
insert(index, value) |
Add an item before a position |
remove(value) |
Delete the first matching value |
pop(index) / pop() |
Delete and return an item / the last item |
count(value) |
Count matching values |
index(value) |
Find the first matching position |
sort() |
Sort the existing list |
reverse() |
Flip the current order |
copy() |
Return a shallow copy |
clear() |
Empty the existing list |
len(scores) and sum(scores) are built-in functions, not list methods. Operations that only change the list return None; pop, count, index, and copy return useful results.
A for Loop Visits Each Item
A loop repeats instructions. Read for score in scores: as “for each item in scores, call it score and run this block”.
Outputs: Score 70, Score 80, Score 90, then Done.
The indented line runs once per item, in list order. The unindented line runs after the loop finishes. You choose the item name; it need not be score.
A Running Total, Step by Step
Start the total at zero. On each visit, add the current item to the previous total.
Running totals: 70, 150, 240. Final total: 240.
For this numeric update, total += score is a shorter way to write total = total + score. Starting total inside the loop would reset it on every visit.
For Loops
An average is the total divided by the number of items. Five prices add to 506, so their average is 506 ÷ 5 = 101.2.
Once we understand the steps, sum(prices) / len(prices) gives the same result. The list must be nonempty; dividing by its zero length would fail.
Practice: Finish the Average
The loop computes a total. Edit the average calculation, then add one more price and rerun. The denominator must adapt to the list length.
The first average should be 101.2. Divide by len(prices), not a fixed number.
range: Repeat for Numbered Steps
range(start, stop) supplies integers from start up to, but not including stop. Use it for numbered repetitions.
The first loop visits 1, 2, 3. The second visits 0, 1, 2: with one input, range() starts at zero.
To visit years 1 through 4, use range(1, 5). Try the endpoint 4 and see which year disappears.
while: Repeat While a Condition Is True
A while loop checks a condition before each repetition. If the condition is True, it runs the indented body and checks again. If the condition is False, it continues after the loop.
Outputs: Tickets left: 3, Tickets left: 2, Tickets left: 1, Finished. The body changes the value used in the condition. At zero, tickets_left > 0 becomes false.
This is called indefinite repetition: a condition controls when to stop, so we do not have to choose the repetition count in advance. It does not mean “run forever”. Try starting at zero: the body runs zero times and only Finished appears.
while: Save Until You Reach a Goal
We have HK$70, save HK$15 per day, and stop when the balance reaches at least HK$100. Count the days as the loop runs; no day count is supplied to the loop.
Outputs: Day 1: HK$85.00, Day 2: HK$100.00, Days needed: 2.
| Check before the next repetition | Condition | Action |
|---|---|---|
| Balance 70 | 70 < 100 is True |
Save 15 |
| Balance 85 | 85 < 100 is True |
Save 15 |
| Balance 100 | 100 < 100 is False |
Leave the loop |
Assume daily_saving is positive. Change the goal to 115 and predict the days needed. If the starting balance already meets the goal, the answer is zero days. This model has no interest or spending.
while: Stop When the List Is Empty
The condition can depend on the current list length. Each pop() removes an item, so the list eventually becomes empty.
Outputs: Removed: 90, Items left: 2, Removed: 80, Items left: 1, Removed: 70, Items left: 0, Finished: [].
pop() takes the last item, so the removal order is 90, 80, 70. Checking the length before each removal prevents popping from an empty list. Try starting with scores = []; no item is removed.
for or while: Choose What Controls Repetition
Use for to visit a collection or a range. Use while when the next repetition depends on a condition. Both can produce the same output.
Both print Day: 1, Day: 2, Day: 3. The for loop gets its next item from the range. In the while loop, our code updates day.
For “visit every score”, choose for. For “keep saving until the goal is met”, choose while. A colon ends either loop header, and indentation marks its body.
Avoid an Infinite Loop: Check the Update
An infinite loop keeps repeating without reaching a stop. In this unfinished sketch, count stays at 1, so the condition stays true:
count = 1
while count <= 3:
print(count)
# Missing update: count never changes.
The sketch is text, not an executable Python box. Run the corrected version:
Outputs: 1, 2, 3, Stopped at: 4. The update belongs inside the loop. It moves the value toward making the condition false; subtracting 1 here would move in the wrong direction.
Before running a while loop, explain its starting value, condition, update, and stopping case. For the savings example, zero or negative daily saving would not reach a higher goal.
Section 4 — Practice: Lists and Repetition
Work from question 1 to 10. Write your code, click Run Code, review the result, then click Submit attempt. An attempt may be wrong: reference answers become available after you submit all 10. Each Python box is independent. Submission progress is saved in this browser.
1. Make and measure a list
Warm-up. Create scores containing 60, 75, and 90 in that order. Print the list, its number of items, and its total.
Write your answer, then run it.
2. Read and replace a score
Warm-up. Print the first and last scores using indexes. Replace the middle score with 85, then print the whole list.
Write your answer, then run it.
3. Add one score and several scores
Warm-up. Append 90 as one item, then extend scores with 85 and 95 as two separate items. Print the final flat list and its length.
Write your answer, then run it.
4. Insert, remove, and keep the removed value
Build your skills. Insert 75 at index 1. Remove the first value equal to 60. Pop the last item into removed. Print removed, then the remaining list.
Write your answer, then run it.
5. Search and sort a separate copy
Build your skills. Print the count of 75 and the first position of 75. Make a copy, sort the copy in ascending order, then print the sorted copy and the unchanged original.
Write your answer, then run it.
6. Visit and number five days
Build your skills. Use a for loop and range to print Day 1 through Day 5. Include day 5.
Write your answer, then run it.
7. Trace a total and calculate an average
Build your skills. Use a for loop to add each amount to a running total and print the total after each addition. After the loop, print the average using the current list length.
Write your answer, then run it.
8. Count down with a while loop
Challenge. Use while to print 3, 2, and 1 on separate lines, then print Done once. Update count inside the loop. Test count=0 afterwards: only Done should appear.
Write your answer, then run it.
9. Save until a target is reached
Challenge. Start at HK$45 and save HK$20 per day until the balance is at least HK$100. Use while, count days, and print each new balance with two decimals. Finally print Days: followed by the count. Test starting at 100 too.
Write your answer, then run it.
10. Process prices until the list is empty
Challenge. Use while and pop() to remove one price per repetition, adding it to a total. Print each running total with two decimals. After the loop, print the empty list and Total: HK$30.00. Test an empty starting list as well.
Write your answer, then run it.
Reference answers are locked until all 10 attempts are submitted.
1. Make and measure a list
scores = [60, 75, 90]
print(scores)
print(len(scores))
print(sum(scores))Expected output
[60, 75, 90]
3
225The list preserves order; len counts items and sum adds numeric values.
2. Read and replace a score
scores = [60, 75, 90]
print(scores[0])
print(scores[-1])
scores[1] = 85
print(scores)Expected output
60
90
[60, 85, 90]Indexes start at zero. Assigning to index 1 replaces the second item without adding an item.
3. Add one score and several scores
scores = [60, 75]
scores.append(90)
scores.extend([85, 95])
print(scores)
print(len(scores))Expected output
[60, 75, 90, 85, 95]
5append adds one item. extend adds each item separately; appending [85, 95] would instead add one inner list.
4. Insert, remove, and keep the removed value
scores = [60, 90, 60, 85]
scores.insert(1, 75)
scores.remove(60)
removed = scores.pop()
print(removed)
print(scores)Expected output
85
[75, 90, 60]Insertion shifts items; removal deletes only the first 60. pop returns 85, while the other 60 remains.
5. Search and sort a separate copy
scores = [75, 60, 75, 90]
print(scores.count(75))
print(scores.index(75))
ordered = scores.copy()
ordered.sort()
print(ordered)
print(scores)Expected output
2
0
[60, 75, 75, 90]
[75, 60, 75, 90]There are two matches, with the first at index zero. Sorting a copy preserves the original list.
6. Visit and number five days
for day in range(1, 6):
print(f"Day {day}")Expected output
Day 1
Day 2
Day 3
Day 4
Day 5range excludes its stop, so use stop 6 to include day 5.
7. Trace a total and calculate an average
amounts = [10, 15, 5]
total = 0
for amount in amounts:
total = total + amount
print(total)
print(total / len(amounts))Expected output
10
25
30
10.0The running total is 10, 25, then 30. There are three items, so the average is 10.
8. Count down with a while loop
count = 3
while count > 0:
print(count)
count = count - 1
print("Done")Expected output
3
2
1
DoneThe test happens before each repetition. At zero it is false, so the loop body is skipped.
9. Save until a target is reached
balance = 45
daily_saving = 20
goal = 100
days = 0
while balance < goal:
balance = balance + daily_saving
days = days + 1
print(f"HK${balance:.2f}")
print("Days:", days)Expected output
HK$65.00
HK$85.00
HK$105.00
Days: 3The target can be exceeded. Three positive saving updates reach 105; a starting balance of 100 needs zero days.
10. Process prices until the list is empty
prices = [5, 10, 15]
total = 0
while len(prices) > 0:
price = prices.pop()
total = total + price
print(f"HK${total:.2f}")
print(prices)
print(f"Total: HK${total:.2f}")Expected output
HK$15.00
HK$25.00
HK$30.00
[]
Total: HK$30.00pop() removes the last item first: 15, 10, then 5. The length test prevents an empty pop; an initially empty list has total zero.
Functions
Functions: Name a Reusable Calculation
A function is a named set of instructions. def defines it. Calling its name with parentheses asks Python to run it.
Outputs: 6, 20. number is a parameter: a name for the input inside the function. In double(3), the input 3 is an argument.
Defining the function does not run its body. Each call supplies an input and runs the calculation.
return Gives a Result Back
return sends a value back to the code that called the function. print() displays a value on the screen. They are different jobs.
Outputs: 105.0, 115.0. We can store and reuse the returned number. The 5% tax is an invented classroom example.
return ends that function call. A function that reaches the end without returning a value gives back None, Python’s “no value” marker.
Two Inputs and Their Order
A function can take more than one input. In these calls, Python matches the inputs to the parameters from left to right.
Outputs: 100, 60, 100. The last call labels its inputs explicitly.
The names inside the function refer to the inputs for that call. Define the function before calling it.
Practice: Finish a Rectangle Function
The area of a rectangle is length × width. Complete the function, then test more than one pair of inputs.
Expected areas: 15 and 10.0. Also test width = 0; the result should be zero. Both lengths must use the same unit.
From a Simple Function to a Sale Calculation
A share is a unit of ownership. Selling shares gives gross proceeds: price × shares. A commission is a transaction fee.
Outputs: 1000, 1.0, 999.0. A rate of 0.001 means 0.1%. Next, put these steps into a reusable function. We assume a fixed sale price and this fee only.
Functions
A function packages logic for reuse. Test representative inputs and check it again when its logic or assumptions change. Here we assume a fixed sale price and only a 0.1% commission.
A share is a unit of company ownership. In this example, gross sale proceeds equal price per share times shares sold. Commission is a transaction fee: 0.1% is 0.001, so a HK$1,000 gross sale has a HK$1 fee. The function returns gross proceeds minus that fee. Prices are example inputs, not current market quotes.
Practice: Make Commission an Input
Finish the function to deduct gross * commission_rate. Test both a zero fee and a 0.1% fee using the same function.
Expected values: $1,000.00 and $999.00. Changing the fee input should change only the fee deduction.
Section 5 — Practice: Functions
Work from question 1 to 10. Write your code, click Run Code, review the result, then click Submit attempt. An attempt may be wrong: reference answers become available after you submit all 10. Each Python box is independent. Submission progress is saved in this browser.
1. Define and call
Warm-up. Define double(number) to return twice its input. Print double(4).
Write your answer, then run it.
2. Reuse a result
Warm-up. Define add_five(number), store add_five(10) in result, then print result and result * 2.
Write your answer, then run it.
3. Two parameters
Warm-up. Define rectangle_area(length, width). Print the areas for (5, 3) and (2.5, 4).
Write your answer, then run it.
4. Label the arguments
Build your skills. Define ticket_bill(price, quantity). Call it using named arguments quantity=3 and price=25, and print the result.
Write your answer, then run it.
5. Repair print versus return
Build your skills. The function should provide a number that can be stored and multiplied. Replace the display instruction inside the function with a return, then print result * 2.
Write your answer, then run it.
6. A fee as an input
Build your skills. Define net_sale(price, shares, fee_rate). Return price * shares minus that amount times fee_rate. Print the results at price 100, shares 10, fees 0 and 0.001.
Write your answer, then run it.
7. Convert inside a function
Build your skills. Define bill_from_text(price_text, quantity_text). Convert the inputs and return the numeric bill. Print its result for “12.50” and “4” with two decimal places.
Write your answer, then run it.
8. Choose a delivery charge
Challenge. Define delivery_fee(order_value): return 0 if the value is at least 100, otherwise return 15. Print the fees for 80, 100, and 120.
Write your answer, then run it.
9. Call a function in a loop
Challenge. Define passes(score) to return whether score is at least 60. Loop over the scores, printing each score and the returned Boolean.
Write your answer, then run it.
10. A discounted bill with delivery
Challenge. Define final_bill(price, quantity, discount_rate). Subtract the discount from the product cost, then add HK$15 delivery only if the discounted bill is below HK$100. Print bills for (40, 3, 0.1) and (25, 2, 0.1) with two decimals.
Write your answer, then run it.
Reference answers are locked until all 10 attempts are submitted.
1. Define and call
def double(number):
return number * 2
print(double(4))Expected output
8def defines the instructions; a call supplies the input and runs them.
2. Reuse a result
def add_five(number):
return number + 5
result = add_five(10)
print(result)
print(result * 2)Expected output
15
30return gives a number back to the caller; print alone would not return that number.
3. Two parameters
def rectangle_area(length, width):
return length * width
print(rectangle_area(5, 3))
print(rectangle_area(2.5, 4))Expected output
15
10.0Both inputs matter; a float input can produce a float area.
4. Label the arguments
def ticket_bill(price, quantity):
return price * quantity
print(ticket_bill(quantity=3, price=25))Expected output
75Named arguments identify the matching parameter even when written in a different order.
5. Repair print versus return
def triple(number):
return number * 3
result = triple(4)
print(result * 2)Expected output
24The original function displays a value and returns None. Returning the calculation lets the caller use 12.
6. A fee as an input
def net_sale(price, shares, fee_rate):
gross = price * shares
fee = gross * fee_rate
return gross - fee
print(net_sale(100, 10, 0))
print(net_sale(100, 10, 0.001))Expected output
1000
999.0The same function handles both assumptions. A 0.001 rate means a 0.1% commission.
7. Convert inside a function
def bill_from_text(price_text, quantity_text):
price = float(price_text)
quantity = int(quantity_text)
return price * quantity
bill = bill_from_text("12.50", "4")
print(f"HK${bill:.2f}")Expected output
HK$50.00Conversion and calculation happen inside the function; formatting happens at the call site.
8. Choose a delivery charge
def delivery_fee(order_value):
if order_value >= 100:
return 0
else:
return 15
print(delivery_fee(80))
print(delivery_fee(100))
print(delivery_fee(120))Expected output
15
0
0The equality boundary qualifies for free delivery under this classroom rule.
9. Call a function in a loop
def passes(score):
return score >= 60
scores = [55, 60, 85]
for score in scores:
print(score, passes(score))Expected output
55 False
60 True
85 TrueFunctions can return Boolean values, not only numbers.
10. A discounted bill with delivery
def final_bill(price, quantity, discount_rate):
subtotal = price * quantity
bill = subtotal * (1 - discount_rate)
if bill < 100:
bill = bill + 15
return bill
print(f"HK${final_bill(40, 3, 0.1):.2f}")
print(f"HK${final_bill(25, 2, 0.1):.2f}")Expected output
HK$108.00
HK$60.00The first discounted bill is 108 and gets no delivery fee; the second is 45 and gets a 15 fee.
Put the Pieces Together
Percentages and One Year of Growth
7% means 7 out of 100: write it as 0.07 in a calculation. A balance grows by adding 7% of its current value.
Outputs: 700.0, 10700.0, 10700.0. Multiplying by 1 + rate combines the original balance and the increase.
For a 5% decrease use −0.05, so the multiplier is 0.95. These are assumptions for a calculation.
Worked Example: HK$10K Summer Savings
Suppose HK$10,000 grows at a constant 7% each year for four years. Each year grows the updated balance, so we multiply by 1.07 four times.
The result is HK$13,107.96. :,.2f combines thousands commas and two decimal places.
This is a hypothetical calculation, not a forecast. Fees, taxes, inflation, and changing annual returns are omitted.
Trace the Savings Year by Year
A loop lets us see how the same calculation develops. The new balance becomes the starting balance for the next year.
Expected balances: 10,700.00 → 11,449.00 → 12,250.43 → 13,107.96.
years + 1 includes year 4 because the range endpoint is excluded. The formula and loop agree to the cent.
Compare Growth Scenarios
Repeat the calculation under three assumed constant annual growth rates. A negative rate reduces the balance.
At −5%: HK$8,145.06. At 0%: HK$10,000.00. At 7%: HK$13,107.96.
These are scenarios, not probabilities or a forecast range. The code applies our assumptions; it does not prove the assumptions will happen.
Practice: Model Changing Annual Returns
Replace the loop update so each annual return changes the current balance. Print the balance after each year. Does a negative year reduce it?
Multiply the current balance by 1 + rate. Expected balances: 10,700.00; 10,165.00; 10,469.95; 10,469.95.
Section 6 — Practice: Put the Pieces Together
Work from question 1 to 10. Write your code, click Run Code, review the result, then click Submit attempt. An attempt may be wrong: reference answers become available after you submit all 10. Each Python box is independent. Submission progress is saved in this browser.
1. Represent a percentage
Warm-up. Store 5% as a numeric rate. Print the rate and 5% of HK$200.
Write your answer, then run it.
2. One year of growth
Warm-up. Starting at HK$1000, calculate the balance after one year at an assumed 5% growth. Print two decimals.
Write your answer, then run it.
3. A negative year
Warm-up. Start at HK$1000 and apply a 10% decrease. Print the updated balance with two decimals.
Write your answer, then run it.
4. Use a power
Build your skills. Calculate HK$1000 growing at an assumed 10% per year for 3 years using **. Print two decimals.
Write your answer, then run it.
5. Trace the three years
Build your skills. Use a loop to calculate the same growth as the previous question. Print the year and updated balance each time.
Write your answer, then run it.
6. Compare scenarios
Build your skills. For HK$1000 over 2 years, loop over assumed rates -0.10, 0, and 0.10. Print each rate as a percentage and the final amount.
Write your answer, then run it.
7. Changing annual rates
Build your skills. Start at HK$1000. Apply annual rates 10%, -10%, and 5% in that order. Print the balance after each year.
Write your answer, then run it.
8. Add a deposit at year-end
Challenge. Start at HK$1000. In each of 2 years, first grow the balance by 5%, then add a HK$200 deposit at year-end. Print both year-end balances.
Write your answer, then run it.
9. Growth followed by an annual fee
Challenge. Start at HK$1000. Each year for 2 years: grow by 5%, then subtract a fixed HK$10 fee. Define a function for one year and call it inside the loop. Print each balance.
Write your answer, then run it.
10. Check a savings goal under assumptions
Challenge. Start at HK$1000, apply rates [0.10, -0.10, 0.05], then print the final balance and Goal met if it is at least HK$1050, otherwise Below goal. Add a Python comment explaining why this is not a forecast.
Write your answer, then run it.
Reference answers are locked until all 10 attempts are submitted.
1. Represent a percentage
rate = 0.05
print(rate)
print(200 * rate)Expected output
0.05
10.0Five percent is 5 divided by 100, or 0.05.
2. One year of growth
balance = 1000
rate = 0.05
balance = balance * (1 + rate)
print(f"HK${balance:.2f}")Expected output
HK$1050.00The multiplier includes the original balance and the increase.
3. A negative year
balance = 1000
rate = -0.10
balance = balance * (1 + rate)
print(f"HK${balance:.2f}")Expected output
HK$900.00A rate of -0.10 gives a multiplier of 0.90.
4. Use a power
principal = 1000
rate = 0.10
years = 3
value = principal * (1 + rate) ** years
print(f"HK${value:.2f}")Expected output
HK$1331.00Each year multiplies by 1.10. Three years use the third power; format the display with two decimal places.
5. Trace the three years
balance = 1000
rate = 0.10
years = 3
for year in range(1, years + 1):
balance = balance * (1 + rate)
print(f"Year {year}: HK${balance:.2f}")Expected output
Year 1: HK$1100.00
Year 2: HK$1210.00
Year 3: HK$1331.00The new balance is the starting point for the next year. The loop and formula give the same displayed final result.
6. Compare scenarios
principal = 1000
years = 2
rates = [-0.10, 0.00, 0.10]
for rate in rates:
value = principal * (1 + rate) ** years
print(f"{rate:.0%}: HK${value:.2f}")Expected output
-10%: HK$810.00
0%: HK$1000.00
10%: HK$1210.00These are separate assumptions, not probabilities. Reset the calculation from the principal for each rate.
7. Changing annual rates
balance = 1000
annual_rates = [0.10, -0.10, 0.05]
for rate in annual_rates:
balance = balance * (1 + rate)
print(f"HK${balance:.2f}")Expected output
HK$1100.00
HK$990.00
HK$1039.50A 10% rise followed by a 10% fall does not cancel; each percentage uses a different starting balance.
8. Add a deposit at year-end
balance = 1000
rate = 0.05
yearly_deposit = 200
for year in range(1, 3):
balance = balance * (1 + rate)
balance = balance + yearly_deposit
print(f"Year {year}: HK${balance:.2f}")Expected output
Year 1: HK$1250.00
Year 2: HK$1512.50Deposit timing matters. A year-end deposit does not earn that same year's growth in this model.
9. Growth followed by an annual fee
def one_year(balance, rate, fee):
return balance * (1 + rate) - fee
balance = 1000
rate = 0.05
fee = 10
for year in range(1, 3):
balance = one_year(balance, rate, fee)
print(f"Year {year}: HK${balance:.2f}")Expected output
Year 1: HK$1040.00
Year 2: HK$1082.00The fixed fee reduces this year's balance and therefore the starting amount for next year.
10. Check a savings goal under assumptions
principal = 1000
annual_rates = [0.10, -0.10, 0.05]
goal = 1050
balance = principal
for rate in annual_rates:
balance = balance * (1 + rate)
print(f"HK${balance:.2f}")
if balance >= goal:
print("Goal met")
else:
print("Below goal")
# The rates are assumed; the code does not establish future returns.Expected output
HK$1039.50
Below goalThe arithmetic checks a stated path. Real outcomes can use other rates and incur additional costs.
Check and Explain Your Work
Errors Are Clues: Read the Last Line
An error message tells us why Python could not follow an instruction. Read its final line, then find the relevant code.
| Error | Typical cause | First check |
|---|---|---|
NameError |
A name has not been defined | Spelling and run order |
TypeError |
The operation does not fit the types | type(...) and conversions |
SyntaxError |
Code is not valid Python | Quotes, parentheses, colons |
IndentationError |
A block is not indented correctly | Spaces at line starts |
A wrong answer can also occur without an error message. Compare outputs with small examples you can calculate by hand.
Practice: Fix a Type Error
Run this cell to see an intentional error. We want numeric addition, giving 350. Convert the numeric text before adding it.
Expected first run: TypeError. Expected after your fix: 350.
Use int(online_sales_text) for this whole-number input. Test "0" and "50" too. A nonnumeric value such as "unknown" cannot be converted this way.
Working with ChatGPT
- ChatGPT can help explain code or suggest a fix.
- You still need to understand Python and verify the suggestion.
- Give it the code, the error, and the expected result.
Vague prompt: “Fix this code.”
Specific prompt:
My code is
revenue = 100 + "250". It raises a TypeError about adding an int and a str. I expected the integer 350. Explain the error and suggest a fix.
Verify a ChatGPT-Suggested Fix
- Run the code and compare with a hand calculation.
- Explain why
int("250")is appropriate for this input. - Ask what happens with
"250.50"or"unknown".
A program can run successfully and still answer the wrong question. Check assumptions, units, and results as well as errors.
Mistakes Library: NASA Mars Climate Orbiter (1999)
On 23 Sep 1999 NASA lost the Mars Climate Orbiter after a navigation error sent it too close to Mars.
Ground software reported thruster impulse in pound-force seconds (lbf·s); the interface specification required newton seconds (N·s). The navigation software treated the values as if they met that specification.
The documented units were not followed, and verification was inadequate. Clear names help, but they do not replace checking the data and conversion.
- Put the unit in the name —
revenue_hkd, notrevenue. - Check units and conversions against the data specification.
Decision Memo — Your First Analyst Output
In this course, use a short memo to connect a calculation to a decision. State what the evidence supports and what remains uncertain.
To: Future Me
From: An ISOM 2600 student
Subject: Test the assumptions behind a four-year savings projection
Recommendation: Compare growth scenarios before choosing how to use the savings.
Evidence: HK$10,000 becomes HK$8,145.06 at −5%, HK$10,000.00 at 0%, or HK$13,107.96 at 7% annual growth for four years.
Caveats: These are assumed constant rates, not forecasts. Fees, taxes, and inflation are omitted.
Next step: Check when the money is needed and model changing annual returns and relevant costs.
Chapter Summary: Core Building Blocks
| Code | Meaning |
|---|---|
x = 4 |
Make x refer to 4 |
int, float, str, bool |
Whole number, approximate number, text, yes/no |
type(x) |
Inspect the type |
+ - * / |
Add, subtract, multiply, divide |
** // % |
Power, floor division, remainder |
int("4"), float("4.5") |
Convert numeric text |
f"{price:.2f}" |
Make text displaying two decimal places |
== != < > <= >= |
Compare values |
Display formatting and numeric rounding are different. round(x, n) returns a rounded value; it is a detail to consult when a task needs it.
Chapter Summary: Decisions and Repetition
| Code | Meaning |
|---|---|
and, or, not |
Combine or reverse Boolean conditions |
if / elif / else |
Choose a branch |
[70, 80, 90] |
A list in order |
len(scores), sum(scores) |
Count items, add numeric items |
scores.append(95), scores.pop() |
Add an item, remove and return the last item |
for score in scores: |
Visit each item |
range(1, 5) |
Integers 1 through 4 |
while balance < goal: |
Repeat while a condition is true |
def double(number): |
Define a function with an input |
return number * 2 |
Send a result back |
Indentation shows which instructions belong to a branch, loop, or function.
Before Moving to Chapter 1
Can you explain and check these without guessing?
- How do
4,4.0, and"4"differ? - Why do
7 / 2,7 // 2, and7 % 2give different results? - Why is
"2" + "3"not 5? How can you make numeric 5? - Which branch runs when a score is exactly at the threshold?
- Why does a running total start before the loop?
- How do
append,extend, andinsertdiffer? - What is returned by
pop, and what is returned bysort? - What makes a
whileloop stop, and can its body run zero times? - How is
returndifferent fromprint()?
Next: Chapter 1 deepens lists, then introduces pandas Series, NumPy, statistics, and plots for second-year business-school students.
Section 7 — Practice: Check and Explain
Work from question 1 to 10. Write your code, click Run Code, review the result, then click Submit attempt. An attempt may be wrong: reference answers become available after you submit all 10. Each Python box is independent. Submission progress is saved in this browser.
1. Fix a name
Warm-up. Python names are case-sensitive. Repair the misspelled name so this prints 20.
Write your answer, then run it.
2. Fix mixed types
Warm-up. The intended numeric answer is 350. Convert the text input before adding.
Write your answer, then run it.
3. Find the missing colon
Warm-up. Repair the syntax so a score of 65 prints Pass.
Write your answer, then run it.
4. Repair indentation
Build your skills. Put the first print inside the if block and keep Done outside. The result at False should be only Done.
Write your answer, then run it.
5. Compare rather than assign
Build your skills. The condition should test whether the label equals YES. Repair the operator, then print Approved at the given input.
Write your answer, then run it.
6. A calculation can run and be wrong
Build your skills. The desired profit is revenue minus cost, not their sum. Fix the code, print the result, and add a comment explaining the mistake.
Write your answer, then run it.
7. An excluded endpoint
Build your skills. The program must visit years 1, 2, 3, and 4. Fix the range and print all four years.
Write your answer, then run it.
8. A total that keeps resetting
Challenge. Move the initialization so all three prices contribute to the final total. Print the correct total.
Write your answer, then run it.
9. Choose the right conversion
Challenge. A suggested fix uses int for a decimal price and still fails. Repair the conversion, print the bill with two decimals, then test price_text=“8.75” yourself.
Write your answer, then run it.
10. Find a units mistake
Challenge. The input price is 250 HK cents per item, and 3 items are bought. Repair the conversion and variable name so the printed bill is in HK dollars. Add a comment with a hand check.
Write your answer, then run it.
Reference answers are locked until all 10 attempts are submitted.
1. Fix a name
price = 10
print(price * 2)Expected output
20Price has not been defined; the existing name is price.
2. Fix mixed types
cash = 100
online_text = "250"
print(cash + int(online_text))Expected output
350A numeric calculation requires numeric values. Here the whole-number text can use int.
3. Find the missing colon
score = 65
if score >= 60:
print("Pass")Expected output
PassA block header ends with a colon.
4. Repair indentation
raining = False
if raining:
print("Take umbrella")
print("Done")Expected output
DoneIndentation changes which instructions belong to the condition.
5. Compare rather than assign
label = "YES"
if label == "YES":
print("Approved")Expected output
ApprovedUse == in the equality test, not assignment =.
6. A calculation can run and be wrong
revenue = 500
cost = 300
profit = revenue - cost
print(profit)
# The original code added spending instead of subtracting it.Expected output
200No exception is needed for a logic error. Check the meaning of the formula.
7. An excluded endpoint
years = 4
for year in range(1, years + 1):
print(year)Expected output
1
2
3
4The stop value is excluded, so it must be one greater than the last desired year.
8. A total that keeps resetting
prices = [10, 20, 30]
total = 0
for price in prices:
total = total + price
print(total)Expected output
60Initialization belongs before the loop; otherwise only the final item survives.
9. Choose the right conversion
price_text = "12.50"
quantity_text = "2"
price = float(price_text)
quantity = int(quantity_text)
print(f"HK${price * quantity:.2f}")Expected output
HK$25.00Decimal price text needs float. Changing the price to 8.75 should produce HK$17.50.
10. Find a units mistake
price_cents = 250
quantity = 3
price_hkd = price_cents / 100
bill_hkd = price_hkd * quantity
print(f"HK${bill_hkd:.2f}")
# 250 cents = HK$2.50; three items cost HK$7.50.Expected output
HK$7.50A correct multiplication can still use the wrong units. Convert cents to dollars before interpreting the bill.
Optional: See Branching as a Flowchart
The diamonds ask the score comparisons in order. Follow the true or false arrows for score 82, then 95 and 69. The drawing cell is already written for you; you do not need to understand its plotting code in Chapter 0.
Optional: Further Practice
Complete the core examples first. These extensions introduce extra tools; they are not prerequisites for moving to Chapter 1.
Debug Yourself: Counting Vowels
In this optional challenge, for letter in text visits one character at a time, and letter.lower() in vowels asks whether that character is a vowel. assert checks a condition and raises an error if it is false. The cell below intends to count the vowels in the phrase "Business Analytics". Its calculation produces an answer that is off by one; the assertion at the end deliberately raises an error until you fix it. Try to spot the bug by reading the loop body carefully before reading the explanation underneath.
The trick: the membership test ch in vowels is case-sensitive, and vowels = "aeiou" contains only lowercase letters. The phrase "Business Analytics" has six vowels — u, i, e, A, a, i — but the uppercase A is invisible to the test, so the buggy version returns 5. The minimal fix is to compare against the lowercased character, e.g. if ch.lower() in vowels:, or equivalently to widen the alphabet to vowels = "aeiouAEIOU". Both produce the correct count of 6, and the hidden assertion will pass.
Interactive Explorer: Compound Interest
This optional extension uses NumPy and matplotlib, which Chapter 1 will explain. You can change the inputs without writing the plotting code. The two values at the top of the cell control how a $10,000 deposit grows over time. Change the annual rate, change the horizon in years, then press Run and watch the curve and the terminal value update. Try a 5 % rate over 10 years for a baseline, then double the horizon to 20 years to see how compounding rewards patience, and finally raise the rate to 10 % to see how a higher return reshapes the curve into a sharper exponential.
Optional: Floating-Point Precision and Rounding
A float stores an approximation. For example, 0.1 + 0.2 produces 0.30000000000000004. An f-string can display two decimal places without changing that underlying value.
round(x, n) returns a new rounded value. Exact halfway values round to even: round(1.5) and round(2.5) both return 2. Binary representation can also affect decimal rounding, such as round(2.675, 2) returning 2.67. These details are optional here. Tasks requiring exact decimal arithmetic need a suitable approach such as decimal.Decimal constructed from text and an explicit rounding rule.
Review Cards — Chapter 0
Try answering before revealing each card. These cards review the core material; advanced precision and plotting details are optional.
It displays a value. Python evaluates a calculation first, so print(2 + 3) displays 5, while print("2 + 3") displays text.
= assigns a value to a name. == compares values and gives a Boolean result.
No. Run bill = price * quantity again to use the updated inputs.
4 is an int, 4.0 is a float, and "4" is a string. The first two compare numerically equal; the text is different.
3.5, 3, and 1. They perform division, floor division, and the remainder operation.
2 ** 3, which gives 8. ^ is not the power operator.
They are strings, so + joins the text into “100250”. Convert to numbers if numeric addition is intended.
Its f prefix tells Python to evaluate expressions inside braces and insert their results into the text.
No. It creates text displaying two decimal places. The original numeric value is unchanged.
float("12.50"). int("12.50") raises an error. Integer-looking text such as “4” can use int.
No. Methods such as .strip() and .upper() return new text. Assign the result if you want to keep it.
A bool: True or False. They are capitalised and have no quotes.
and requires both to be true; or requires at least one; not reverses the result.
The >= 90 test is false; >= 80 is the first true test, so grade B is assigned and later branches are skipped.
They identify the instructions inside a branch, loop, or function. An unindented line is outside that block.
Before the loop. Resetting it inside the loop loses the earlier items.
len counts items; sum adds them. A nonempty list average is sum(scores) / len(scores).
1, 2, 3, 4. The endpoint 5 is excluded.
A parameter is an input name in the function definition. An argument is an input supplied in a call.
return gives a result back to the caller and ends the call. print displays a value. A function without a returned value gives None.
The arithmetic applies our assumed rates. It does not establish that the rates will happen or include omitted costs.
Index 0 selects the first item. Index -1 selects the last item of a nonempty list.
append adds one item at the end; extend adds each supplied item; insert adds one item before a position.
remove(value) deletes the first matching value. pop(index) deletes and returns the item at a position; without an index, it takes the last item.
No. count gives the number of matches; index gives the first matching position. A missing value has count zero, but looking up its index raises ValueError.
reverse flips the current order without sorting. sort changes the existing list and returns None; keep the list name and print it after sorting.
copy returns a new outer list; a second name still refers to the same list. A shallow copy shares any nested objects. clear removes all items from the existing list.
No. A while loop repeats according to a condition rather than a supplied iteration count. It stops when the condition is false; it can also run zero times.
Check the starting state, the condition, the update, and the stopping case. In these examples the update moves the condition toward False.
Quiz Review — Chapter 0
Work from question 1 to 10. Write your code, click Run Code, review the result, then click Submit attempt. An attempt may be wrong: reference answers become available after you submit all 10. Each Python box is independent. Submission progress is saved in this browser.
Question 1
Print the types of count, price, and code. Then print 4 tickets cost HK$10.00 using an f-string and a calculated bill. Keep code as text.
Write your answer, then run it.
Question 2
You have 29 items. A box holds 6. Print full boxes and leftovers. Each full box costs HK$3 to pack; each leftover item costs HK$1. Print the total packaging charge.
Write your answer, then run it.
Question 3
Clean the item name, convert numeric text, and print BOOK: 2 items, HK$37.50.
Write your answer, then run it.
Question 4
A student gets a discount only if the bill is at least HK$100 AND they have a student card. Print Discount or No discount. Test the given boundary, then bill=99.
Write your answer, then run it.
Question 5
Loop over the scores. Calculate the total and the number scoring at least 60. Print the average with one decimal place, then the passing count. Do not hardcode the list length.
Write your answer, then run it.
Question 6
Define a function discounted_bill(price, quantity, rate) that returns the product cost after a discount. Print bills for (20, 3, 0.1) and (12.5, 2, 0) with two decimals.
Write your answer, then run it.
Question 7
Start at HK$2000 and apply rates [0.05, -0.10, 0.02]. Print the balance after each step. Add a comment stating one omitted real-world cost.
Write your answer, then run it.
Question 8
A ChatGPT suggestion says the code below computes the average. Fix its formula, print the correct average, and add a comment with an independent hand calculation. Do not accept the suggestion only because it runs.
Write your answer, then run it.
Question 9
Start with prices [12.5, 8.0, 9.5]. Add 5.0 at the end and remove the item whose value is 8.0. Create a separate list with the remaining prices in ascending order. Print the updated original list, the ordered list, and the average price with two decimal places. The original must keep its updated order.
Write your answer, then run it.
Question 10
Define days_to_goal(start, daily_saving, goal), returning how many daily deposits are needed to reach or exceed the goal. All inputs are in HK dollars and daily_saving is positive. Count deposits until the target is met, without supplying a fixed repetition count. Print the results for (50, 15, 200) and (200, 15, 200). Include a hand-check comment. This model has no interest or spending.
Write your answer, then run it.
Reference answers are locked until all 10 attempts are submitted.
Question 1
count = 4
price = 2.5
code = "0042"
print(type(count))
print(type(price))
print(type(code))
print(f"{count} tickets cost HK${count * price:.2f}")Expected output
<class 'int'>
<class 'float'>
<class 'str'>
4 tickets cost HK$10.00A count, a price, and an identifier have different types and purposes.
Question 2
items = 29
capacity = 6
full_boxes = items // capacity
leftover = items % capacity
charge = full_boxes * 3 + leftover * 1
print(full_boxes)
print(leftover)
print(f"HK${charge:.2f}")Expected output
4
5
HK$17.00Four complete boxes hold 24 items; five remain. The two packing charges add to 17.
Question 3
item_text = " book "
price_text = "18.75"
quantity_text = "2"
item = item_text.strip().upper()
price = float(price_text)
quantity = int(quantity_text)
print(f"{item}: {quantity} items, HK${price * quantity:.2f}")Expected output
BOOK: 2 items, HK$37.50The displayed receipt is text; the bill is calculated using numeric values.
Question 4
bill = 100
has_student_card = True
if bill >= 100 and has_student_card:
print("Discount")
else:
print("No discount")Expected output
Discount>= includes the boundary; and requires the card as well.
Question 5
scores = [50, 60, 70, 80]
total = 0
passes = 0
for score in scores:
total = total + score
if score >= 60:
passes = passes + 1
print(f"{total / len(scores):.1f}")
print(passes)Expected output
65.0
3The total is 260 over four values. Three scores meet the inclusive passing threshold.
Question 6
def discounted_bill(price, quantity, rate):
return price * quantity * (1 - rate)
print(f"HK${discounted_bill(20, 3, 0.1):.2f}")
print(f"HK${discounted_bill(12.5, 2, 0):.2f}")Expected output
HK$54.00
HK$25.00A 10% discount keeps 90% of the original bill. A zero discount preserves the full amount.
Question 7
balance = 2000
rates = [0.05, -0.10, 0.02]
for rate in rates:
balance = balance * (1 + rate)
print(f"HK${balance:.2f}")
# This scenario omits transaction fees.Expected output
HK$2100.00
HK$1890.00
HK$1927.80Each rate acts on the updated balance. The rates are assumed, and actual costs need separate modelling.
Question 8
scores = [60, 80, 100]
average = sum(scores) / len(scores)
print(average)
# Hand check: (60 + 80 + 100) / 3 = 80.Expected output
80.0The original code computes a total rather than an average. A successful run does not establish correctness.
Question 9
prices = [12.5, 8.0, 9.5]
prices.append(5.0)
prices.remove(8.0)
ordered = prices.copy()
ordered.sort()
print(prices)
print(ordered)
print(f"HK${sum(prices) / len(prices):.2f}")Expected output
[12.5, 9.5, 5.0]
[5.0, 9.5, 12.5]
HK$9.00The three remaining prices total 27. A sorted copy provides ascending order without rearranging the updated original.
Question 10
def days_to_goal(start, daily_saving, goal):
balance = start
days = 0
while balance < goal:
balance = balance + daily_saving
days = days + 1
return days
print(days_to_goal(50, 15, 200))
print(days_to_goal(200, 15, 200))
# Hand check: 50 + 10 * 15 = 200; starting at 200 needs zero deposits.Expected output
10
0The condition controls repetition. Ten deposits reach the goal; when the starting balance already reaches it, the body runs zero times.
Comments and Reading Order
Python normally runs these lines from top to bottom.
A
#starts a comment: a note for people reading the code. Python ignores the rest of that line.Expected output:
30. Changing a comment does not change the calculation; changingpricedoes.