SDD10 — Pre-defined Functions
- I can use Python's pre-defined functions to create substrings, convert between characters and ASCII codes, convert a float to an integer, and calculate a modulus
- I can explain what each of these four pre-defined functions does and predict its output for a given input
- I can select the correct pre-defined function to solve a given problem
- I can extract a substring from a string using slicing and using
split() - I can convert a character to its ASCII code with
ord()and an ASCII code to its character withchr() - I can explain why
int()truncates a float rather than rounding it, and predict its output for a given value - I can calculate and interpret the result of the modulus operator
%
global. What happens when the function runs?Key vocabulary
% operator.int().Four more pre-defined functions
What is a pre-defined function?
A pre-defined function is a function built into the programming language itself, ready to use immediately without ever being written or defined by the programmer — this is exactly what separates it from the sub-programs covered in SDD7, which a programmer designs and defines from scratch. National 5 introduced three: random, round, and length (Python's len()). Higher adds four more, each solving a specific, common problem: creating substrings, converting between a character and its ASCII code, converting a float to an integer, and calculating a modulus.
Creating substrings: slicing and split()
A substring is a shorter piece taken from within a larger string. Python offers two distinct ways to create one. Slicing extracts characters by position, using square brackets with a start and end index, e.g. word[0:4] takes the first four characters. A negative index counts backwards from the end, so word[-3:] takes the last three characters. The split() function instead breaks a whole string into a list of substrings wherever a chosen delimiter character appears, e.g. splitting a sentence on a space produces a list of its individual words. Slicing is used when you know the exact position of the substring you want; split() is used when you want to divide a whole string into pieces wherever a particular character occurs.
Converting between characters and ASCII codes
Every character has a numeric ASCII code (covered in CS4). Python provides ord() to convert a single character to its ASCII code, and chr() to convert an ASCII code back to its character. Both take exactly one argument and return the other representation — they are exact inverses of each other.
Converting a float to an integer
The int() function converts a floating-point number to an integer. Critically, int() does not round — it truncates, simply discarding everything after the decimal point, regardless of how large the discarded fraction is. This makes it entirely different from National 5's round() function, which rounds to the nearest whole number. If a problem genuinely requires rounding before converting to a whole number, round() must be applied first, and only then, if needed, int() — using int() alone where rounding was intended is a common source of quietly wrong answers.
Modulus: finding a remainder
The modulus operator, written % in Python, calculates the remainder left over after dividing one integer by another — there is no separate named function for this, unlike the other three. Modulus is frequently used to test whether a number divides evenly into another (a remainder of 0 means it does), to check whether a number is even or odd (number % 2 == 0 is True for even numbers), or to work out how many items are left over once a quantity has been packed into equally-sized groups.
word[0:4]
sentence.split(" ")ord("C") → 67
chr(67) → "C"int(68.75) → 6823 % 5 → 3Worked examples
itemName = "Chocolate":
firstFour = itemName[0:4] lastThree = itemName[-3:]
sentence = "Higher Computing Science"
words = sentence.split(" ")firstFour is "Choc", lastThree is "ate", and words is ["Higher", "Computing", "Science"] — slicing picked out characters by position, while split() broke a whole string apart wherever a space occurred.itemName = "Chocolate" firstLetter = itemName[0] asciiCode = ord(firstLetter) backToChar = chr(asciiCode)
itemName[0] uses slicing (a single index) to extract the first character, "C". ord("C") then converts that character to its ASCII code.asciiCode is 67, and chr(67) converts it straight back to "C" — confirming ord() and chr() are exact inverses of each other.averagePrice = 68.75 wholePence = int(averagePrice) roundedPence = round(averagePrice)
int() simply discards everything after the decimal point of 68.75, no matter how close it is to the next whole number. round(), by contrast, rounds to the nearest whole number.wholePence is 68 (truncated), while roundedPence is 69 (rounded) — the same starting value produces two different results depending on which function is used.stockLevel = 29 boxSize = 6 leftover = stockLevel % boxSize
leftover is 5 — 5 bars remain once 4 full boxes of 6 have been packed (4 × 6 = 24, and 29 − 24 = 5).itemCount, write a single Python expression using the modulus operator that evaluates to True if itemCount is an even number, and False if it is odd.
- Assuming
int()rounds. It truncates —int(68.75)is68, not69. If rounding is genuinely needed, useround()instead, or before converting withint(). - Mixing up
ord()andchr().ord()goes character → code;chr()goes code → character. Passing the wrong type to either raises aTypeError. - Forgetting slicing's end index is exclusive.
word[0:4]takes characters at positions 0, 1, 2, and 3 — not position 4. - Confusing
split()with slicing.split()breaks a whole string apart on every occurrence of a delimiter; slicing extracts one substring from known positions. They solve different problems and are not interchangeable. - Treating modulus as if it were normal division.
%returns only the remainder, e.g.23 % 5is3, not4.6— pupils sometimes confuse it with/.
When asked to write code using a pre-defined function, name the exact function required rather than a general description — "use ord()" earns more credit than "convert the letter to a number". When tracing int(), always show the truncation explicitly (e.g. "68.75 becomes 68, not 69") rather than just writing the final answer, since examiners are checking that truncation — not rounding — was understood.
Task Set A — Core questions
word = "Computing", what is the value of word[0:4]?split() does?ord("A")?chr(97)?int(45.99) evaluate to?int(64.86)?23 % 5?isEven that takes one formal parameter, number, and returns True if number is even, otherwise False, using the modulus operator.def isEven(number):
return number % 2 == 0
int() and round() when applied to 68.75, and why confusing the two is a risk. (3 marks)Task Set B — Extension
split() to read data from a CSV file. Suggest how split() might be used twice — once with one delimiter, and again with a different delimiter — to turn a whole CSV file's text into individual pieces of data.-7 % 3 in Python. This may not be the answer you expect — research how Python's modulus operator behaves with negative numbers, and suggest why this could cause a bug if code were transferred from a different programming language.split() would succeed at creating the substrings needed, but slicing alone could not — because the exact positions of the substrings are not known in advance.Higher Computing Science → Software Design & Development → SDD10
Double period — first lesson back after the summer break, and a genuinely dense single-lesson topic (four distinct functions), so the extra time is needed. Consider a short settling-in/retrieval activity before the warm-up given the break since SDD9.
Suggested timing: 5 min warm-up + vocab · 25 min notes + func-grid summary card (live-run each function in the Python shell as it's introduced, rather than only showing static code) · 30 min examples 1–4 · 10 min "now you try" · 40 min Task Set A · Task Set B as homework/extension.
Key misconception: pupils very reliably assume int() rounds, because round() was the only float-to-whole-number tool they met at National 5 — deliberately contrast int(68.75) vs round(68.75) side by side live, not just in the slides.
SQA command words covered: explain, describe, predict, identify, write code.
Extension suggestion: Extension 2 (negative modulus) is a genuine "gotcha" worth demonstrating live in the Python shell for stronger pupils — -7 % 3 surprises almost everyone the first time.
Cross-reference: reviewed a colleague's equivalent file-handling materials (Lessons 7–8) ahead of building SDD11/SDD12 next — confirmed the manual double-split() approach (no csv module) and dataclass dot-notation access are both consistent with this course; flagged one bug in that material (concatenating a non-string dataclass field directly with + without str(), which raises a TypeError) to avoid repeating when SDD12 covers writing CSV output.