• 📖 Cover
  • 📚 Contents
  • Ch 0
  • Ch 1
  • Ch 2
  • Ch 3
  • Ch 4

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.

  1. Values and variables — names, int, and float
  2. Calculations — arithmetic and the order of operations
  3. Text — str, conversion, and f-strings
  4. Decisions — comparisons, Boolean logic, and if
  5. Lists and repetition — list methods, for, and condition-controlled while loops
  6. 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:

  1. Read the short explanation and predict the result.
  2. Run the code after Python finishes loading.
  3. Change one thing and run it again.
  4. 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.

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; changing price does.

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.

Submitted: 0 / 10

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.

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.

Check your result

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.

Check your result

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.

Submitted: 0 / 10

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.

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.

Check your result

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?

Check your result

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

Important

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.

Check your result

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.

Submitted: 0 / 10

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.

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.

Python reference: list methods

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.

Check your result

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.

Python reference: the while statement

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.

Submitted: 0 / 10

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.

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

Note

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.

Check your result

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.

Submitted: 0 / 10

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.

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?

Check your result

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.

Submitted: 0 / 10

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.

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

  1. Run the code and compare with a hand calculation.
  2. Explain why int("250") is appropriate for this input.
  3. 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)

Warning

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, not revenue.
  • Check units and conversions against the data specification.

NASA investigation, pp. 16–17 and 24–25 (printed pages)

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, and 7 % 2 give 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, and insert differ?
  • What is returned by pop, and what is returned by sort?
  • What makes a while loop stop, and can its body run zero times?
  • How is return different from print()?

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.

Submitted: 0 / 10

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.

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.

Submitted: 0 / 10

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.

Next →Python Essentials

 

Prof. Xuhu Wan · HKUST ISOM · Introduction to Business Analytics