DO NOT COPY OR SHARE - A3Tech / NCTI course material for enrolled students only
A3Tech logo

Introduction to Python Programming · A3Tech

Module 4

Today you will

Repeat code with loops: a checkout that keeps taking items, and a price table in three lines.

  1. Repeat code with a while loop and stop it with break.
  2. Repeat a set number of times with for and range().
  3. Keep a running total in a loop.
  4. Recognise and fix a loop that never stops.

Deep dive A: why do we need loops?

A loop repeats code for us. Without one, printing a countdown means typing the same line over and over:

no_loop.py
print("Patties left: 3")
print("Patties left: 2")
print("Patties left: 1")
print("Sold out")
Output
Patties left: 3
Patties left: 2
Patties left: 1
Sold out

That works for 3, but what about 300? Or when we don't know how many times in advance, like a checkout where the customer keeps adding items? A loop does the repeating, however many times it takes.

with_loop.py
stock = 3
while stock > 0:
    print("Patties left:", stock)
    stock = stock - 1
print("Sold out")
Output
Patties left: 3
Patties left: 2
Patties left: 1
Sold out

Deep dive B: the while loop - repeat as long as...

while works like an if that keeps coming back. It checks the condition; if it's True, it runs the indented block, then goes back to the top and checks again. It stops the moment the condition is False.

Same four parts as an if: the word while, a condition, a colon, and an indented block.

while_basic.py
count = 1
while count <= 3:
    print("Round", count)
    count = count + 1
print("Finished, count is now", count)
Output
Round 1
Round 2
Round 3
Finished, count is now 4

Trace it round by round - this is how to read any loop:

Roundcount at the topcount <= 3 ?What happens
11Trueprints Round 1, count becomes 2
22Trueprints Round 2, count becomes 3
33Trueprints Round 3, count becomes 4
-4Falseloop ends, jump to the last line

Deep dive C: counters and running totals

A counter goes up by 1 each time round the loop. A running total adds a new amount each time. Both use the same trick: the variable appears on both sides of =.

count = count + 1 means: take the old value of count, add 1, and store the answer back in count.

running_total.py
total = 0
items = 0

total = total + 5.00     # beef patty
items = items + 1
total = total + 4.00     # coconut tart
items = items + 1

print(items, "items, total EC$", total)
Output
2 items, total EC$ 9.0

Shortcut: total += 5 means exactly the same as total = total + 5. You'll see it a lot in real code. -= works for taking away.

plus_equals.py
stock = 10
stock -= 3       # same as stock = stock - 3
stock += 5       # delivery arrived
print("Stock:", stock)
Output
Stock: 12

Deep dive D: loops that never stop (and how to escape)

If the condition never becomes False, the loop runs forever. This is called an infinite loop. The usual cause: nothing inside the loop changes the variable in the condition.

infinite_fixed.py
stock = 3
while stock > 0:
    print("Patties left:", stock)
    stock = stock - 1      # without this line, stock is always 3 - forever!
print("Sold out")
Output
Patties left: 3
Patties left: 2
Patties left: 1
Sold out

To stop a runaway program: press Ctrl + C in the terminal, or the red Stop button in Thonny. Every programmer does this regularly - it's not a disaster.

Deep dive E: while True and break

while True: means "loop forever" - the condition is always True. We use it when we don't know when to stop until something happens inside the loop, like the customer typing done.

break jumps straight out of the loop, to the first line after it.

break_basic.py
count = 0
while True:
    count = count + 1
    print("Scanning item", count)
    if count == 3:
        print("Last item - stopping")
        break
print("Checkout finished")
Output
Scanning item 1
Scanning item 2
Scanning item 3
Last item - stopping
Checkout finished

That's exactly how the checkout works: while True keeps asking for prices, and if entry == "done": break is the way out. Notice float(entry) - prices have cents, so we convert to a float, not an int.

Deep dive F: the for loop and range()

for repeats once for each item in a sequence. With range(), that sequence is a set of numbers, so it's perfect when you know how many times to repeat.

for_basic.py
for qty in range(1, 4):
    print("Order of", qty)
Output
Order of 1
Order of 2
Order of 3

Each time round, the variable qty takes the next number automatically - no counter to add to, so no risk of an infinite loop.

The rules of range():

CodeGivesWhy
range(5)0, 1, 2, 3, 4starts at 0, stops BEFORE 5
range(1, 6)1, 2, 3, 4, 5start at 1, stop BEFORE 6
range(0, 20, 5)0, 5, 10, 15third number is the step
range(5, 0, -1)5, 4, 3, 2, 1a negative step counts down
range_examples.py
print(list(range(5)))
print(list(range(1, 6)))
print(list(range(0, 20, 5)))
print(list(range(5, 0, -1)))
Output
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[0, 5, 10, 15]
[5, 4, 3, 2, 1]
WeekCounter.py
week = 0
for qty in range(7, 365, 7): # Range first then the STEP or Gap
    week += 1
    print("Day Number", qty, " is in Week Number", week)
Output
Day Number 7  is in Week Number 1
Day Number 14  is in Week Number 2
Day Number 21  is in Week Number 3
...
Day Number 364  is in Week Number 52

for also works on text, one letter at a time:

for_letters.py
for letter in "PATTY":
    print(letter)  
Output
P
A
T
T
Y

use .lower() or .upper() to change the case of the letters. mini string manipulation 

Deep dive G: while or for - which one?

UseWhenShop example
forYou know how many times (or have a set of things)Print prices for 1 to 10 patties
whileYou repeat until something happensKeep taking items until the customer says done

Both can do the same job, but the right one makes the code shorter and safer. Compare these two countdowns:

while_vs_for.py
# with while: you manage the counter yourself
n = 3
while n > 0:
    print(n)
    n = n - 1

# with for: range does it for you
for n in range(3, 0, -1):
    print(n)
Output
3
2
1
3
2
1

Deep dive H: lining up the price table

The price table uses two new f-string tricks to make neat columns:

  • {qty:>3} - make it 3 characters wide and push it to the right (> = right, < = left)
  • {price:6.2f} - 6 characters wide, 2 decimal places
alignment.py
price = 5.00
for qty in [1, 10, 100]:
    print(f"no width: {qty} patties")
for qty in [1, 10, 100]:
    print(f"width 3:  {qty:>3} patties  EC${qty * price:7.2f}")
Output
no width: 1 patties
no width: 10 patties
no width: 100 patties
width 3:    1 patties  EC$   5.00
width 3:   10 patties  EC$  50.00
width 3:  100 patties  EC$ 500.00

The two format codes


Everything after the colon inside { } is a format instruction.

{qty:>3}

3 reserves 3 characters of space for the value.
> pushes the value to the right side of that space.
So 1 becomes " 1", 10 becomes " 10", and 100 becomes "100". Every value takes up exactly 3 characters, which is why the columns line up.

{qty * price:7.2f}

Python does the math first: qty * price gives 5.0, 50.0 and 500.0.
f formats the result as a decimal number.
.2 shows exactly 2 digits after the decimal point, so you get 5.00 and never 5.0.
7 makes the whole thing 7 characters wide, counting the digits, the dot and the padding spaces:
" 5.00" is 3 spaces plus 4 characters.
" 50.00" is 2 spaces plus 5 characters.
" 500.00" is 1 space plus 6 characters.

Numbers line up on the right by default, which is how the prices line up on the decimal point.

Things that often trip people up

The width is a minimum. If a value is too long, say qty = 1000 with width 3, Python doesn’t cut it off. It prints all 4 digits and the column just shifts.
Numbers line up on the right by default, so {qty:3} and {qty:>3} give the same result. The > makes it explicit. Use < for left and ^ for center.
“EC$” is ordinary text in the string. The formatting only applies to what’s inside the braces.

1. The checkout loop

Type a few prices, then type done.

01_checkout.py
# shop.py - Module 4: a checkout that keeps going until "done"
total = 0
items = 0
while True:
    entry = input("Item price (or 'done'): ")
    if entry == "done":
        break
    total = total + float(entry)
    items = items + 1
    print(f"  Running total: EC${total:.2f}")

print(f"{items} items. Total: EC${total:.2f}")

2. A price table with for

Three lines of loop make a whole table.

02_price_table.py
# Module 4 - a price list for 1 to 10 patties with a for loop
price = 5.00
print("Qty   Price")
for qty in range(1, 11):
    print(f"{qty:>3}   EC${qty * price:6.2f}")

Words to know

WordMeaning
LoopCode that repeats
whileRepeat as long as a condition is True
forRepeat once for each item or number
range(1, 11)The numbers 1 to 10
breakLeave the loop now
Running totalA variable that grows each time round the loop

Bug hunt

This loop never stops. Press Ctrl+C, then fix it so it counts down 5, 4, 3, 2, 1 and says "Sold out".

03_loop_bug.py
# BUG HUNT - this loop never stops! (press Ctrl+C to stop it)
# Fix it so it counts down 5, 4, 3, 2, 1 and then says "Sold out".
stock = 5
while stock > 0:
    print("Patties left:", stock)
print("Sold out")
Hints (open only if stuck)
  1. What needs to change each time round the loop?
  2. Take 1 away from stock inside the loop.

Practice

Homework 4 (5%): stock.py

Simulate a day's stock. It must:

Submit your .py file and a screenshot of it running, before the next module.

MarkMeans
5Runs and has everything
3Runs with parts missing, or has errors
1Started
0Not submitted

Quiz 4

Check yourself here, then take the graded quiz in the quiz section of robotics.a3tech.uk (two tries).

1. How many times does this print Hi?
for i in range(3):
    print("Hi")
2. What numbers does range(1, 5) give?
3. What does break do?
4. Why does this never stop?
stock = 5
while stock > 0:
    print(stock)
5. What is total at the end?
total = 0
for p in [5, 4, 3]:
    total = total + p

ADDITIONAL - STREAMLIT APP - SNEAK PEEK 4

The price table as a web page. A slider picks how many rows, and the same for loop builds the table.

price_table_app.py
# price_table_app.py - a for loop in a Streamlit app
# Run it with:  streamlit run price_table_app.py

import streamlit as st

st.title("Mama J's Bakery - Price Table")

price = 5.00
max_qty = st.slider("Show prices up to how many patties?", min_value=1, max_value=24, value=10)

for qty in range(1, max_qty + 1):
    st.write(f"{qty} patties: EC${qty * price:.2f}")
Output
See the browser. Drag the slider - e.g. at 3:
1 patties: EC$5.00
2 patties: EC$10.00
3 patties: EC$15.00