FP1 practical mock exam — the continuous-assessment exams in Python, marked on the spot (rule of 8 included)

Has this ever happened to you: your function works with the example in the statement, you hand it in feeling calm and the VPL gives you a 6? It is almost always a case you did not try: a day without readings, an empty list, a tie. This mock exam recreates the FP1 practical exams inside the website: you choose the exam (the three continuous-assessment ones or the resit) and a version, and you program in the SergioLearns environment, which runs Python in your browser. As in the exam, you press Evaluate and get a mark out of 10 with a comment for each failing test.

There are 12 original exercises: three versions (A, B and C) of each exam, with the same format, the same difficulty and the same times as the real ones (35 minutes for the first and 40 for the others). Before the mock exam I explain what the exam is like; afterwards, how it is marked (with the famous «maximum mark: an 8»), how to split your time, the cases that fail most and the cheat sheets you could check.

Take the mock exam

Choose the exam and the version (or «At random») and press Start: the exam takes up the whole window, with the statement on the left and the environment on the right. Complete the .py file, try it with Run and press Evaluate when you think it is ready. When you press Hand in (or time runs out) the last version of your code is marked.

The mock exam needs JavaScript. Below you will find what the exam is like and what each exercise covers.

The first time you press Run or Evaluate, the browser downloads Python (about 12 MB). It takes a few seconds; after that it is fast and stays saved for your next visit.

Your code never leaves your computer: it runs in your browser and is saved there while you work (if you reload the page, it is still there). When you hand in, the draft is deleted.

What the FP1 practical exam is like

The FP1 practical exams were done in VPL, the programming activity of aep26 (the exams Moodle). Each one is one exercise: a statement with the context (which data structure you are given), the function you have to write, an example and some automatic tests that give the mark. There were two sittings with different statements; here you have three versions of each exam.

ExamWhat they ask forFilesTimeMarks
Exam 1One function on lists, matrices and tuples (with a helper or recursive)cinema.py + a drawing module35 min10
Exam 2One function on nested dictionaries, tuples and sets, with error answers ("NO AUTH"…)main.py + example.py with the data40 min10
Exam 3One function with regular expressions that reads a file and writes another with formattingexam.py + test_text.txt + help modules40 min10
ResitOne file with two functions from the whole syllabusOne .py40 min5 + 5

What surprises you most the first time is the time: 35 or 40 minutes for one function sounds like a lot, but between reading the statement, understanding the data structure and fighting the odd cases, it flies. This drawing is exactly what you will see in the environment:

The pieces of the environmentThe file you complete (with its if __name__) is marked; the others are given. Run launches your file and shows what it prints; Evaluate runs the tests and gives the mark with a comment per failure. From the eleventh evaluation, each one subtracts 0.1.What you see in the environmentcinema.pyyou complete it and it is markedwith its if __name__ == "__main__":screen.py · example.py  given: they draw or bring datatest_text.txt  exam 3: the input file  Run  Evaluatelaunches your .py: you see whatits __main__ prints (no mark)runs the weighted tests:mark /10 + a comment per failureFrom the 11th evaluation: −0.1 eachWhen you hand in, the last version is marked for free
Unlike FP2, there is no separate tryout file: you test by hand in your own file's __main__.

Notice one difference with FP2: here there is no separate tryout file. The .py you complete comes with an if __name__ == "__main__": at the end with the example from the statement; Run launches that file and shows you what it prints. You can change that block to try your own cases: it is not marked. The Evaluate tests import your function and call it with their own data.

Before writing a single line, press Run with the file as it is. You will see the NameError of the missing function, but you will also check that Python is loaded and that the given files work.

What each exam covers

The continuous-assessment exams followed the pace of the course: the first one, around week 8 (after Recursion); the second one, at the end of Associative containers; and the third one, with Strings, Regular expressions and Text files. The resit can touch anything. This is what comes up and where to revise it:

ExamTopicsMock exam versionsRevise with
Exam 1T02-T10: functions, lists and tuples, matrices, recursionA Free seats at the cinema · B Boxes inside boxes (recursive) · C Temperatures of the weekLists and tuples, Matrices, Recursion
Exam 2T11: associative containersA An author’s top reader · B Buses between two stops · C The short film festival winnerAssociative containers
Exam 3T12-T14: strings, regex and filesA The times in a timetable · B Email addresses by domain · C The shopping receiptStrings, Regular expressions, Text files
ResitThe whole syllabusA Flight codes and free seats · B Rotate a matrix and save it · C Digit sums and groupsThe three above and Functions

The statements are original: the real ones only told me which data structure they gave, what was asked and how much time there was. If you want to revise the test part, there is the FP1 theory mock exam.

How it is marked

Each exercise has 5 or 6 weighted tests that add up to 10. A test calls your function with some data and compares what it returns (or what it writes to the file) with what is expected; if it matches, you add its weight; if not, you get nothing from that test and a comment tells you what failed. The mark is the sum of the weights of the tests you pass.

A real example: if in Temperatures of the week you forget that a day may have no readings, min([]) raises an error and the two tests with an empty day fail. The environment tells you like this:

1: Your code raises ValueError: min() iterable argument is empty (temperatures.py, line 7).
3: Your code raises ValueError: min() iterable argument is empty (temperatures.py, line 7).

Those two tests are worth 2.5 and 1.5, so the mark is 10 − 2.5 − 1.5 = 6. A single forgotten case, four marks gone.

The rule of 8

In almost every real exam there was a note like «you are advised to write a helper function; if you do not, the maximum mark will be an 8», or «if you use the help function instead of your own pattern, the maximum mark will be an 8». In the mock exam, that rule is one more test worth 2 marks:

  • Exam 1 (A and C): the requested function has to call a helper function of yours.
  • Exam 1 (B): the function has to be recursive (it calls itself or a recursive helper).
  • Exam 3: you cannot use the help module (re_help), which gives you the pattern ready-made.
  • Resit C: digit_sum has to be recursive (1.5 of its 5 marks).

That test only counts if the result is also right, so an empty helper gains you nothing. If in Free seats you do everything inside find_seats, you pass every test except that one and get an 8:

From the tests to the markTwo real runs: Temperatures without the empty-day case fails two tests (2.5 and 1.5) and gets 6; Seats without a helper function passes everything except the 2-mark test of the rule of 8 and gets 8.Each test is worth its own shareTemperatureswithout the «day without readings» case2.51.51.51.5126 / 10Seatsall in one function, no helper2.51.51.51.5128 / 10test passedfailed test: its marks do not count
A single forgotten case can bring down several tests; the rule of 8 is just one more 2-mark test.

Evaluations count

As in the VPL, you can evaluate as often as you like, but the first 10 of each exercise are free and, from the 11th on, each one subtracts 0.1 from that exercise’s mark. The final marking when you hand in does not count. Some numbers so you can see it:

EvaluationsPenaltyIf the tests give 10
1-10010
122 × 0.1 = 0.29.8
155 × 0.1 = 0.59.5
2010 × 0.1 = 19

Evaluating after every line you change. Use Run (which does not count) to try the example and your own cases, and save the evaluations for when you think it is ready.

How to use the environment

  • Run launches your .py (its __main__) and shows the output in the console. If there is an error, you get the traceback and a «Go to <file>, line N» button.
  • Evaluate runs the tests and shows each one with a pass or fail mark, the mark and the evaluation counter.
  • Helpers: in the mock exam they start switched off (no autocomplete or bracket closing), as in the VPL. You can switch them on, but get used to programming without them.
  • Cheat sheet: opens the Python cheat sheet and, in exam 3 and the resit, the regex, files and formatting one too.
  • Full window: the exam takes up the whole screen; drag the dividers to give more room to the statement or the console, use Full screen (the four-corners button) to fill the whole screen and Article to read this text again without losing the clock.
  • Hand in marks the last version of each exercise and gives you the mark, with the solution and its explanation.

On a phone, the exam is split into three tabs: Statement, Code and Result. It can be done, but the real exam is with a keyboard: practice on a computer. And if you want to program without a clock, the same environment is free in Python playground.

How to split your time

With 35 or 40 minutes there is no room to start from scratch twice. A split that works:

Time splitThree time bars: exam 1 in 35 minutes, exams 2 and 3 in 40 and the resit in 40 with two functions. In all of them, a few minutes to read, most of the time to program, a block to evaluate and fix and a few minutes to review at the end.A possible way to split the timeExam 1 · 35 minreadfunction and helperevaluate and fixreviewExams 2 and 3 · 40 minreadthe functionevaluate and fixreviewResit · 40 minreadfunction 1 + evaluatefunction 2 + evaluatereview0510152025303540min
Evaluate early: the comment of each failed test tells you which case you are missing.
  1. Read (4-6 min): understand the data structure. Write in a comment what each thing is (books: code -> (title, author, year, {genres})) and what the function returns in each case, including the error ones.
  2. Program (14-18 min): first the normal case, which is the one in the example; press Run and compare with the output in the statement.
  3. Evaluate and fix (10-12 min): evaluate and read the comments of the failing tests. Each comment tells you which case you are missing.
  4. Review (5-6 min): edge cases (empty, tie, a single element), the rule of 8 and that no test print is left inside the function.

In the resit there are two 5-mark functions in the same time: do the one you see more clearly first, evaluate it and move on to the other. One whole function is worth more than two halves.

The cases that fail most

The tests of each version are designed for the usual mistakes. These are the ones that cost the most marks:

ExamCaseWhat happens if you forget it
1Empty list or matrix, row without a gap, day without readingsIndexError, ValueError from min/max or division by zero
1Numbering from 1 (rows, seats)Everything is shifted by one position
2The order of the error answers ("NO ORIG" before "NO DEST")You return the wrong error
2Ties and numeric order of text ("3" before "12")sorted puts "12" before "3"
2Changing the data you are givenThe tests that check it does not change fail
3\b and the limits of the patternYou take pieces of longer numbers (123:45)
3Upper case, repeats and a sentence’s final full stopYou count the same address twice or put the full stop in the domain
3Amounts with float1.15 + 0.80 + 2.35 + 3.40 gives 7.699999999999999: work in cents
3The newline of writeAll the lines stuck together: write does not add it
Resitsearch instead of fullmatch"XIB3245" looks like a valid code

Common mistakes

  • Returning a list when a tuple is asked for (or the other way round). [('Monday', 18, 24, 21.4)] is not equal to [['Monday', 18, 24, 21.4]]: the tests compare types.
  • Printing instead of returning. If your function does print(result) and not return result, the test gets None.
  • Opening the file without encoding="utf-8". In the exam the text has accents and «€»: always give it the encoding.
  • Rounding before comparing. In The short film festival winner, comparing means that are already rounded can pick the wrong short: round only when you return.
  • A helper that is not used. The rule of 8 checks that the requested function calls it: writing it and not using it does not count.
  • Leaving the if __name__ == "__main__": broken. It is not marked, but if it has a syntax error, the whole file fails.

Writing the function inside the if __name__ == "__main__":. The tests import your module and that block does not run on import: the function would not exist. Write it above, outside it.

Watch it step by step in Python Tutor

Python Tutor runs the code line by line and draws the variables, the lists and the call stack. Choose Python 3. This is the solution to Boxes inside boxes with a small box, perfect to see recursion in action:

def box_summary(box):
    items, weight, deepest = 0, 0, 0
    for thing in box:
        if isinstance(thing, list):
            o, p, h = box_summary(thing)
            items += o
            weight += p
            deepest = max(deepest, h)
        else:
            items += 1
            weight += thing
    return (items, weight, deepest + 1)


box = [2, [1, [5]]]
print(box_summary(box))
(3, 8, 3)

What to watch step by step:

  1. In the first call, thing is 2: it is an item, so items becomes 1 and weight 2.
  2. With [1, [5]] a second frame of box_summary appears on top of the first one: the outer call waits on the o, p, h = … line.
  3. Inside, [5] opens a third frame. It is the deepest box: it returns (1, 5, 1) because it has no boxes inside (deepest is still 0).
  4. On the way back, the second frame adds (1, 5, 1) to its own and returns (2, 6, 2); the first one adds it and returns (3, 8, 3). Notice that deepest keeps the maximum, not the sum.

Cheat sheet: what you could check

In the exam you could check a Python 3 cheat sheet and, in the third one, a regular expressions, files and formatting one. These are ours, covering the same things in our own words. In the mock exam you have them on the Cheat sheet button of the environment.

Python cheat sheet FP1

What you could check in the exam, in our own words: syntax, strings, lists, matrices, dictionaries, sets and functions.

The basics

x = 7; y = 2.5; s = "hello"; ok = Trueint, float, str and bool
7 // 2 → 3 7 % 2 → 1 2 ** 3 → 8 7 / 2 → 3.5floor division, remainder, power and division
int("42") float("3.5") str(7) round(2.675, 2)convert and round
if x > 0 and not done: … elif …: … else: …and, or, not; elif chains
for i in range(1, 10, 2): … while n > 0: …range(start, end not included, step)
break continue passleave the loop, skip to the next turn, do nothing

Strings

s.upper() s.lower() s.strip() s.title()return another string (they are immutable)
s.split(",") "-".join(parts)split into a list / join a list of strings
s.find("ab") → -1 si no está s.count("a") s.replace("a", "b")find does not raise; index does
s[1:4] s[-1] s[::-1] len(s)slice, last character, reversed, length
c.isdigit() c.isalpha() c.isupper() "ab" in scheck characters and containment

Lists and tuples

l.append(x) l.insert(0, x) l.pop() l.remove(x)append, insert, pop the last, remove a value
sorted(l, reverse=True) l.sort() sorted(l, key=lambda t: t[1])sorted returns another; sort changes the same one
t = (3, "a") a, b = t (5,)tuple: immutable; it unpacks; a one-item tuple needs a comma
[x * 2 for x in l if x > 0]comprehension with a filter
b = l[:] b = list(l) import copy; copy.deepcopy(m)shallow copy and deep copy (nested lists)
sum(l) max(l) min(l) len(l) enumerate(l, 1) zip(a, b)handy built-in functions

Matrices (lists of lists)

m = [[0] * 3 for _ in range(2)]create 2 × 3 (never [[0] * 3] * 2: shared rows)
len(m) len(m[0]) m[f][c]rows, columns and one element
for f in range(len(m)): for c in range(len(m[f])): …walk by indexes
[[m[f][c] for f in range(len(m))] for c in range(len(m[0]))]transpose

Dictionaries and sets

d = {"a": 1} d["b"] = 2 d.get(k, 0) k in dget with a default; in looks at the keys
for k, v in d.items(): … d.keys() d.values() d.pop(k)walk and delete
d[k] = d.get(k, 0) + 1 d.setdefault(k, []).append(x)count and group
s = set() s.add(x) a | b a & b a - bset: no repeats; union, intersection, difference
{k: v for k, v in d.items() if v > 0} {x % 3 for x in l}dictionary and set comprehension

Functions and recursion

def f(a, b=1): return a + bdefault parameter; without return it returns None
return x, y → a, b = f()return several values (it is a tuple)
def fact(n): if n <= 1: return 1 return n * fact(n - 1)base case first; the call gets closer to the base case
isinstance(x, list)know whether an element is another list (nested structures)
if __name__ == "__main__": …what only runs when that file is launched

Regex, files and formatting cheat sheet FP1

The cheat sheet of the third exam and the resit, in our own words: patterns, re functions, files and formatting with width.

Patterns

\d \w \s \D \W \Sdigit, letter/digit/_, space; in upper case, the opposite
. [aeiou] [A-Z0-9] [^,]any character, one from the list, range, any except
+ * ? {3} {2,4}one or more, zero or more, optional, exactly 3, from 2 to 4
+? *?lazy version: as short as possible
^ $ \bstart, end and word boundary
(\d+) (?:ab)+ a|b \.group, non-capturing group, alternative, a real dot
r"\d{8}[A-Z]"write patterns as r"…" strings

re functions

re.search(p, s) re.match(p, s) re.fullmatch(p, s)anywhere, at the start, the whole string (None if not)
re.findall(p, s)list of matches (with groups: tuples of groups)
for m in re.finditer(p, s): m.group(0), m.group(1), m.start()walk the matches with their groups
re.sub(p, r"\1-\2", s) re.split(r"[,;]\s*", s)replace (with groups) and split
re.findall(p, s, re.IGNORECASE)case-insensitive

Text files

with open("data.txt", encoding="utf-8") as f: texto = f.read()read everything (it closes by itself)
for line in f: line.rstrip("\n")line by line (each with its newline)
f.readlines() texto.split("\n")list of lines
with open("out.txt", "w", encoding="utf-8") as f: f.write(f"{x}\n")"w" creates or empties; "a" appends; write adds no newline
FileNotFoundErrorthe file does not exist (are you in the right folder?)

Formatting

f"{n:>3}" f"{s:<16}" f"{s:^10}"right in 3, left in 16, centred in 10
f"{x:.2f}" f"{x:8.2f}" f"{n:02d}"2 decimals, in 8 with 2 decimals, 2 digits with zeros
"=" * 10 "{:>5}".format(n)repeat a character; format as an alternative
c // 100, c % 100 → f"{c // 100}.{c % 100:02d}"amounts in cents, without float errors

Summary

ExamTimeWhat cannot be missing
Exam 135 minThe helper function (or the recursion) and the empty cases
Exam 240 minUnpacking the tuples properly, the error answers in their order and not changing the data
Exam 340 minYour own pattern, the formatting with width and the newline of each write
Resit40 minTwo 5-mark functions: finish one before starting the other

Three ideas to keep:

  1. The mark is the sum of the tests you pass: one forgotten case (empty, tie) can bring down several at once.
  2. The rule of 8 is a 2-mark test: the helper that gets called, the recursion or your own pattern.
  3. Run a lot and evaluate little: from the 11th evaluation, each one costs 0.1.

Once you have it, try the test part in the FP1 theory mock exam, or see all the mock exams in Exams.

Keep goingAll Python articles

Did this article help you? Here is how you can support SergioLearns →