…
…
Python Programming Fundamentals · Lesson 9 / 40 · Algorithms and loops
PreviewIn this lesson you will
You can read the explanation without an account. The exercises and quiz at the end of the lesson are for members.
A new employee has started at Corner Café. Ada is explaining how to give change at the register, but the employee asks right away: "What do I do if the customer hands over too little money?" The instructions did not cover this case. In this lesson you will learn to plan a job before writing code, to try out the plan, and then to turn it into Python line by line.
Ada's instructions were short: "Subtract the total from the money the customer gave, and hand back the difference." The employee's question caught a gap in the instructions. If the customer pays $2.50 for a $4.25 order, there is no change to give; and if they pay exactly $4.25, saying "change 0" would be odd. A human employee closes this gap by asking. A computer does not ask: it cannot make up a step that is not in the instructions, and it does only what you wrote. That is why programmers think first and write second.
At the end of the lesson, the program you write will print this when a customer pays $5 for a $4.25 order; it will also give the right answer for an underpayment and an exact payment:
OutputChange: $0.75In this lesson you will be able to:
There is no new Python command in this lesson. You will use everything you have learned so far (variables, math, f-strings, if, elif, else); what is new is the work you do before writing the code.
A sequence of steps that is followed to finish a job, written out clearly, and that ends at some point is called an algorithm. The word comes from the name of the mathematician al-Khwarizmi, who lived in the 9th century. A recipe, the assembly guide of a cupboard, or directions to an address are all algorithms. A good algorithm has three properties: each step is clear (it cannot be understood in two ways), the steps are done in a certain order, and the algorithm ends at some point.
An algorithm does not depend on a programming language. The same algorithm can be written in Python, in another language, or in English on paper. A program is an algorithm written in a programming language. Ada's latte recipe is an algorithm too: first the coffee is ground, then it is brewed. Put the steps below in the right order.
Put the steps of the latte-making algorithm in the right order.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
All algorithms are built from just three building blocks. Sequence: steps are done one after another in the order they are written. Selection: one of several paths is followed depending on a condition ("if the milk has run out, open a new one"). Repetition: a group of steps is done again a set number of times or until a condition is met ("whisk until the milk is frothy"). You already know two of the Python equivalents of these three:
| Building block | What it does | Python equivalent |
|---|---|---|
| Sequence | Does the steps in the order written | The top-to-bottom order of lines (lesson 1) |
| Selection | Chooses a path depending on a condition | if, elif, else (lessons 6–8) |
| Repetition | Does a group of steps again | Loops (lessons 10 and 11) |
Example 1 (case): The latte recipe with the three building blocks. Let's write Ada's recipe with a few capitalized keywords. Plain lines show sequence, the IF line shows selection, and the REPEAT line shows repetition; the square brackets on the right mark which building block it is:
OutputBEGIN
Prepare the espresso [sequence]
IF there is no milk: [selection]
Open a new milk carton
Heat the milk [sequence]
REPEAT until the milk is frothy: [repetition]
Whisk the milk
Pour the milk over the espresso [sequence]
Serve the latte
ENDPay attention to the indentation: "Open a new milk carton" is done only if there is no milk, and "Whisk the milk" is done again and again until the milk is frothy. Just like the if block in Python, the indentation shows which structure a step belongs to. To tell which building block a sentence describes, look at the words: "if" and "unless" announce a selection; "for each …", "while …", and "until …" announce a repetition. Now you try.
Which building block does each sentence describe?
For each row, pick its match from the list, then check.
You could notice the gap in Ada's instructions while writing the code too, but most of the time you do not. While you write code, your mind deals with two jobs at once: what is to be done, and Python's rules (colons, indentation, quotes). That is why we first write a plan that answers only the question "what is to be done". This plan is called pseudocode: steps written in plain English, without having to follow the rules of a programming language.
Pseudocode is divided into three parts:
| Part | Question it asks | In the change request |
|---|---|---|
| INPUT | What information do we have? | The total and the money the customer paid |
| PROCESS | What will be calculated, what decision will be made? | Is the payment less than, equal to, or more than the total? What is the difference? |
| OUTPUT | What will be printed on the screen? | An underpayment, exact payment, or change message |
In pseudocode we use a few capitalized keywords: INPUT, IF … THEN, ELSE, REPEAT, PRINT. To put a value into a box, we use an arrow: difference ← paid − total means "calculate the difference and put it into the difference box". This is exactly the assignment of lesson 2; in Python it is written as =. We use an arrow in pseudocode so as not to carry the = and == mix-up into the plan.
Example 2 (case): The change plan. Ada's request is this: "If the money paid is less than the total, print the amount missing; if equal, print 'Exact payment'; if more, print the change." Let's write the plan:
OutputINPUT: total, paid
IF paid < total THEN:
PRINT "Underpayment" and the difference (total − paid)
ELSE IF paid = total THEN:
PRINT "Exact payment"
ELSE:
PRINT "Change" and the difference (paid − total)While writing the plan, the employee's question was answered by itself: you cannot finish the selection step without writing the line "is the payment less than the total?" Now suppose we skipped the plan and went straight to "print the difference". The first attempt would be a single line:
total = 4.25
paid = 2.5
print(paid - total)Output-1.75The program raised no error, but a negative number appeared on the screen; the employee at the register is surprised: "Am I supposed to give the customer minus $1.75?" This is the most common problem of code written without a plan: a forgotten case. Thinking that writing a plan is a waste of time is a common mistake; here the plan showed us a bug before any code was written.
Another mistake is to think that pseudocode has a strict "correct spelling" like Python. It does not. The same plan could also be written like this:
OutputTake the total and the money paid.
If the payment is less, say how much is missing.
If the payment is equal to the total, say "Exact payment".
If none of these, work out the change and say it.Both plans are valid. There is only one test: is each line unambiguous, and could an employee carry out this line without asking any questions? A line like "sort out the money" fails this test; "print the difference paid − total" passes.
When the plan is ready, writing the code becomes much easier, because each pseudocode line corresponds to one or more Python lines. The method is this: you write the steps of the plan inside the code as comment lines starting with #, then you add the Python lines of that step under each comment. Comments do not change how the program runs (lesson 1), but they tell you and everyone who reads the code "which step of the plan these lines are". In all the exercises from now on you will see this format: # 1. Get the inputs, # 2. ....
First try it with a short plan: at Corner Café, orders of $10 or more get 10 percent off. Match each pseudocode line with its Python line.
Which Python line does each line of the discount plan correspond to?
For each row, pick its match from the list, then check.
Now let's turn the plan of Example 2 into Python. We made the two parts of the pseudocode into two comment lines, and wrote the Python lines under them. The three paths of the plan became the if, elif, and else branches.
# 1. Get the inputs total = 4.25 paid = 5 # 2. Check the payment and print the result if paid < total: print(f"Underpayment: ${total - paid:.2f}") elif paid == total: print("Exact payment") else: print(f"Change: ${paid - total:.2f}")
OutputChange: $0.75The paid = total in the pseudocode became paid == total in Python: a comparison needs two = characters. In pseudocode you can use spaces and phrases such as "money paid"; in Python a variable name cannot have spaces, so we write paid. Follow the program step by step below. First look at which code lines the two comment lines cover, then at how the if and elif conditions turn out false and are skipped and the else branch runs.
Run the code line by line: see which line runs next, the variable boxes and the output.
# 1. Get the inputs total = 4.25 paid = 5 # 2. Check the payment and print the result if paid < total: print(f"Underpayment: ${total - paid:.2f}") elif paid == total: print("Exact payment") else: print(f"Change: ${paid - total:.2f}")
The plan has three paths; to see each one run, change the money the customer paid. At each value, a different branch of the program runs.
Change the money the customer paid: which path of the plan runs?
Pick a value; predict the output first, then look.
1# 1. Get the inputs2total = 4.253paid = 545# 2. Check the payment and print the result6if paid < total:7 print(f"Underpayment: ${total - paid:.2f}")8elif paid == total:9 print("Exact payment")10else:11 print(f"Change: ${paid - total:.2f}")
Change: $0.75
Faded lines didn't run with this value. 2.5 is less than the total: the first branch runs and prints the missing $1.75. 4.25 equals the total: the first condition is false, the second is true. 5 is more: both conditions are false, and the else branch prints the change. Because each line of the plan corresponds to a branch, all three cases are covered.
Let's put what we have done so far into an order you can repeat for every new request:
| Step | What you do | In the change example |
|---|---|---|
| 1 | Read the request; write the inputs and the output | Input: total, paid. Output: a one-line message |
| 2 | Write the decisions and the order of the process in pseudocode | Less, equal, more: three paths |
| 3 | Trace the plan by hand with a small example | 4.25 and 5: "Change: $0.75" should come out |
| 4 | Write the Python line under each step | Under # 1. two assignments, under # 2. the chain |
| 5 | Try every path of the plan with an input | 2.5, 4.25, 5 (the boundary value from lesson 7) |
The fifth step is important: trying a single value tests only one path. The change program has three paths, so at least three tries are needed: less than the total, equal to the total, and more than the total.
Example 3 (outside the case): A cinema ticket. A cinema's rule goes like this: "Under 12: $3, student: $4, everyone else: $6; if the show is before 14:00, $1 off." First the plan:
OutputINPUT: age, is student, show hour
IF age < 12 THEN price ← 3, ELSE IF student THEN price ← 4, ELSE price ← 6
IF hour < 14 THEN price ← price − 1
PRINT "Ticket: price"There are two separate decisions in the plan: one chooses the base price, and the other applies a discount to it. The second decision does not depend on the first, so it becomes a separate if, not an elif. Let's turn it into Python:
# 1. Get the inputs age = 30 student = False hour = 11 # 2. Decide the base price if age < 12: price = 3 elif student: price = 4 else: price = 6 # 3. Apply the matinee discount if hour < 14: price = price - 1 # 4. Print print(f"Ticket: ${price:.2f}")
OutputTicket: $5.00Let's apply the fifth step: try every path of the plan with an input, predict the result in advance, and then run the program.
age | student | hour | Expected | Path that runs |
|---|---|---|---|---|
| 10 | False | 15 | Ticket: $3.00 | Under 12, no discount |
| 20 | True | 13 | Ticket: $3.00 | Student (4), matinee (−1) |
| 30 | False | 20 | Ticket: $6.00 | Everyone else, no discount |
Now it is your turn to add a new step to the plan. In the cell below, steps 1 and 2 are ready; steps 3 and 4 have only their comments.
1. Write the code for steps 3 and 4 and run it: you should see Ticket: $5.00.
2. Add a new step to the plan: write the comment # 3b. $1.50 off for ages 65 and over and add its code under it.
3. Try age = 70 and hour = 20: you should see Ticket: $4.50.
Try it now· not graded; doesn't affect progress
Build the link between plan and code from the other direction too: the lines below belong to the change program in Example 2, but they are mixed up. Look at the pseudocode and put them in the right order.
Put the lines of the change program in the right order according to the plan.
Click the lines in order; to undo one you placed wrong, click it in the list below.
Shuffled lines
Your order
You wrote the plan, but how will you know it is correct? The way to find out before writing any code is to run the plan on paper with a small example. At each step, you write down the value the variables take in a table; this table is called a trace table. It is the paper version of the "Follow step by step" blocks you have used so far: you do what the computer does. A trace table is especially useful in plans with repetition, because in a repetition the same lines run many times with different values, and it gets hard to keep the result in your head.
Example 4 (case): Finding the cheapest price. Ada wants to find the price of the cheapest item on the menu. The plan goes like this: tentatively accept the first price as "cheapest", then look at the prices in turn; if you see a cheaper one, make it the new "cheapest".
Outputcheapest ← first price
FOR EACH price, REPEAT:
IF price < cheapest THEN:
cheapest ← price
PRINT cheapestThis plan has all three building blocks: sequence (the starting value first, the printing at the end), repetition (for each price), and selection (is it cheaper?). Let's trace the plan with the prices 4.25, 2.00, 3.00, and 1.25. At the start, cheapest is 4.25:
| Round | Current price | Is price < cheapest? | cheapest after the round |
|---|---|---|---|
| 1 | 4.25 | 4.25 < 4.25: no | 4.25 |
| 2 | 2.00 | 2.00 < 4.25: yes | 2.00 |
| 3 | 3.00 | 3.00 < 2.00: no | 2.00 (unchanged) |
| 4 | 1.25 | 1.25 < 2.00: yes | 1.25 |
When the repetition ends, the PRINT step prints 1.25 on the screen. Notice the third row: even though 3.00 is cheaper than 4.25, it is more expensive than the current cheapest (2.00), so the box does not change. You will write the Python version of this plan in lesson 12, after you learn loops and price lists. Now read the table yourself: match the value at each moment.
The cheapest-price plan runs with the prices 4.25, 2.00, 3.00, 1.25. What is in the cheapest box at each moment?
For each row, pick its match from the list, then check.
The most common mistake in plans with repetition is to think that the value in a box starts from scratch every round. In fact, each round starts with the value the previous round left behind. Trace the plan below.
What does this plan print on the screen?
cents ← 0
REPEAT 4 times:
cents ← cents + 25
PRINT centsRemember the third property of an algorithm: it ends. Thinking that a repetition ends by itself is also a common mistake. A plan that says "REPEAT while …" stops only if there is a step inside the repetition that changes the condition. What happens when the plan below runs?
What happens when this plan runs?
price ← 6 REPEAT while price is greater than 5: PRINT price END
So when you write a plan with repetition, ask two questions: "What changes in each round?" and "Will this change make the condition false some day?" If there is no answer to either, the plan does not end. In lesson 11 you will see its Python form, the infinite loop.
Corner Café has started deliveries. The request: "Add 4 minutes per kilometer of travel to the preparation time; if the total passes 30 minutes, tell the customer it may be late." Plan: INPUT distance and preparation time · time ← preparation + distance × 4 · IF time > 30 THEN PRINT the message with a warning, ELSE PRINT only the time. Each plan step became a comment in the code.
# 1. Get the inputs distance_km = 6 prep_min = 12 # 2. Work out the delivery time total_min = prep_min + distance_km * 4 # 3. Print the message depending on the time if total_min > 30: print(f"Estimated time: {total_min} min, may be a little late") else: print(f"Estimated time: {total_min} min")
OutputEstimated time: 36 min, may be a little lateTrace the plan by hand: 12 + 6 × 4 = 12 + 24 = 36 (multiplication first, lesson 3). 36 > 30 is true, so the message with the warning runs. At 4 kilometers the time is 28, and the else branch runs.
A university has this rule: "The average is 40 percent of the midterm plus 60 percent of the final. If the final is below 50, the student fails whatever the average; otherwise, they pass if the average is 50 or above." When you write the plan, the first question is "should the final threshold be asked before the average?": yes, because the threshold applies in every case. Code written without a plan looks only at the average and wrongly passes this student.
# 1. Get the inputs midterm = 60 final = 45 # 2. Calculate the average average = midterm * 0.4 + final * 0.6 # 3. Check the final threshold first, then the average final < 50: result = average >= 50: result = : result = (f)
Putting the steps in the wrong order. Someone who follows the recipe "brew the tea, boil the water, put it in a cup" to the letter tries to brew tea with cold water. Python also runs the lines in the order they are written, and it cannot read a value that has not been put into a box yet. In the code below, we want to print the discounted total, but the print line comes before the calculation:
total = 4.25
print(to_pay)
to_pay = total * 0.9OutputTraceback (most recent call last):
File "<kod>", line 2, in <module>
print(to_pay)
^^^^^^
NameError: name 'to_pay' is not definedRead the message from the bottom (lesson 5): on line 2, the name to_pay is not recognized. The name is spelled correctly; the problem is that when Python reaches line 2, line 3 has not run yet. To fix it, move the calculation line above the print line. Adding to_pay = 0 at the start silences the error but prints 0 on the screen; that is hiding the bug, not fixing it. A sneakier form of this bug does not even give an error message: if a calculation is done before the decision that affects it, the program runs but prints a wrong result. The way to guard against both is the same: after writing the plan, trace it step by step with a small example and check that each step relies on the results of the steps before it.
# 1. … comments.Next lesson: In the plans we wrote REPEAT but could not turn it into code; in the next lesson you will learn Python's first tool for repetition: for.
Exercises and quiz are for members
This lesson has 7 coding exercises and a 10-question quiz. Sign up free to solve them, save your progress and move on to the next lesson.
OutputAverage: 51.0 · Result: Failed (final below 50)