Edexcel International Advanced Level Computer Science, point 7.1.1
This is a practical topic for Unit 2: you must be able to select and use each construct in Python 3. The specification refers to the Programming Language Subset (PLS) document for the exact features allowed, so use that alongside these notes.
Flow control is the order in which a program's statements are carried out.
a. Sequence
Statements run one after another, in the order written.
name = input("Name: ")
greeting = "Hello, " + name
print(greeting)
The order matters: greeting uses name, so name must be set first.
b. Selection
A condition decides which statements run.
temp = int(input("Temperature: "))
if temp >= 25:
feel = "Hot"
elif temp >= 15:
feel = "Warm"
else:
feel = "Cold"
print(feel)
ifruns its block when the condition is true.elif("else if") is tested only if the earlier conditions were false.elseruns when none were true.- Indentation shows which statements belong to each branch.
- Nested selection: an
ifinside another. - Test the highest threshold first when conditions overlap.
Match-case
A match statement compares one value against a list of patterns, and runs the block for the first one that matches. It's a tidy alternative to a long if...elif chain that keeps testing the same variable.
day = input("Day: ").lower()
match day:
case "saturday" | "sunday": # | means "or"
print("Weekend")
case "friday":
print("Nearly the weekend")
case other: # the default: matches anything
print("Weekday")
- Each
casegives a pattern. Patterns can be joined with|(or). - The last case is the default, run when nothing else matched. It can be written
case other:orcase _:and is optional. - A guard adds a condition to a case with
if, for ranges:
temp = 18
match temp:
case temp if temp >= 25:
feel = "Hot"
case temp if temp >= 15:
feel = "Warm"
case other:
feel = "Cold"
print(feel) # Warm
c. Count-controlled iteration
Repeats a set number of times: a for loop.
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1 to 5
print(i * i)
for i in range(10, 0, -2): # 10, 8, 6, 4, 2
print(i)
for item in ["a", "b", "c"]: # each item in a collection
print(item)
range(stop)goes from 0 up to but not includingstop.range(start, stop, step)can count in steps and downwards.- A loop inside a loop (nested) repeats the inner one fully for each outer pass.
d. Condition-controlled iteration
Repeats until a condition changes, when the number of repeats isn't known: a while loop.
total = 0
number = int(input("Number (0 to stop): "))
while number != 0:
total = total + number
number = int(input("Number (0 to stop): "))
print(total)
- The condition is tested before each pass, so the body may never run.
- Something inside the loop must change the condition, or it never ends (an infinite loop).
breakleaves the loop early, andcontinueskips to the next pass.- Python has no
do ... until. Usewhile True:with abreakfor a loop that must run at least once:
while True:
password = input("Password: ")
if password == "secret":
break
e. Exception handling for built-in exceptions
An exception is an error that happens while the program runs. Without handling, it stops the program with an error message. Exception handling lets the program catch the error and respond.
try:
age = int(input("Age: "))
print(100 / age)
except ValueError:
print("Please enter a whole number")
except ZeroDivisionError:
print("Age can't be zero")
else:
print("OK")
finally:
print("Finished")
try: the code that might fail.except: what to do for a particular exception.else: runs only if no exception occurred.finally: runs always (for example to close a file).
Common built-in exceptions
| Exception | Cause |
|---|---|
ValueError |
Right type, wrong value: int("abc") |
TypeError |
Wrong type: "a" + 1 |
ZeroDivisionError |
Dividing by zero |
IndexError |
List index out of range |
KeyError |
Dictionary key not found |
FileNotFoundError |
File doesn't exist |
NameError |
Variable not defined |
UnboundLocalError |
A local variable is used before it has a value (for example, changing a global inside a function without declaring it) |
AttributeError |
An attribute or method doesn't exist for that object: (5).upper() |
EOFError |
input() reaches the end of the input with nothing to read |
ArithmeticError |
The general error for calculation problems (ZeroDivisionError is one kind) |
Exception |
The base class: catches almost any error, so use it only as a last resort |
These are the exceptions listed in the Programming Language Subset for the exam.
Catch specific exceptions, not a bare except:, so other errors aren't hidden.
A retry loop with exception handling
Keep asking until the user names a file that exists:
while True:
name = input("File name: ")
try:
f = open(name)
break # it opened, so leave the loop
except FileNotFoundError:
print("No file called", name, "- try again")
print(f.readline())
f.close()
Worked example
Task: write a number-guessing game. The secret number is 7, the player has at most 5 guesses, anything that isn't a whole number is rejected, and each guess gets "Too low" or "Too high".
secret = 7
found = False
for attempt in range(1, 6): # count-controlled: at most 5 guesses
while True: # condition-controlled: until a number is typed
try:
guess = int(input("Guess: "))
break
except ValueError: # exception handling
print("Type a whole number")
if guess == secret: # selection
print("Correct in", attempt, "guesses")
found = True
break
elif guess < secret:
print("Too low")
else:
print("Too high")
if not found:
print("Out of guesses: it was", secret)
It uses all five constructs: sequence (the order of the blocks), selection (if, elif, else), a condition-controlled loop (while, repeating until a number is typed), a count-controlled loop (for, at most 5 guesses), and exception handling (try/except).
Exam tip: choose for when the number of repeats is known and while when it isn't. Indent carefully, and make sure a while loop's condition can change. Name the exception in an except clause, and say what it handles. Practise typing code with no help from the IDE, since Unit 2 is a practical exam.
Check yourself
When would you use a while loop instead of a for loop?
When the number of repetitions isn't known in advance, so the loop continues until a condition changes.
What does range(2, 10, 3) produce?
2, 5, 8.
What is the difference between a syntax error and an exception?
A syntax error breaks the language rules and stops the program running at all. An exception is an error that happens while the program runs, and it can be caught with try/except.
Which exception does int("abc") raise?
ValueError.
What does the finally block do?
It runs whether or not an exception occurred, for example to close a file.