SDD  ·  Software Design & Development

Predefined Functions

Lesson 11 of 18 Approx 60 min Requires: SDD5 Variables & Data Types, SDD6 Input & String Operations
Learning intentions
  • Understand what a predefined function is and why programmers use them
  • Use round() to round a number to a specified number of decimal places
  • Use len() / LENGTH() to find the length of a string
  • Use random.randint() / RANDOM() to generate a random integer within a given range
Success criteria
  • I can explain what a predefined function is and state the benefit of using one
  • I can use round(value, decimal_places) to round a number to a specified number of decimal places
  • I can use len(string) to find the number of characters in a string
  • I can import the random module and use random.randint(low, high) to generate a random integer
  • I can write the SQA pseudocode versions: ROUND(), LENGTH(), and RANDOM()
Warm up — what do you already know?

Answer before the lesson begins. These check prior knowledge from earlier lessons — it's fine if you're unsure.

1. In Python, round() and len() are examples of what kind of function?

2. Which function would you use to count the number of characters in "password"?

3. What is the result of 10 / 3 in Python 3?

Key vocabulary

predefined function
A function that is already written and built into the programming language. You call it by name rather than writing the code yourself.
argument
A value passed into a function when it is called. For example, in round(3.7, 1) the arguments are 3.7 and 1.
return value
The result that a function sends back to the program after it has been called. For example, round(3.7, 1) returns 3.7.
string length
The number of characters in a string. Spaces, digits and punctuation all count as characters.
module
A file of pre-written Python code that adds extra functions. The random module must be imported with import random before its functions can be used.
inclusive range
A range where both the lower and upper limits are possible results. random.randint(1, 6) can return both 1 and 6.

Predefined Functions

What is a predefined function?

A predefined function (also called a built-in function) is a piece of code that has already been written for you by the language designers. Instead of writing the logic yourself, you simply call the function by name, pass in any values it needs (called arguments), and receive a return value back.

For example, to round a number to two decimal places you could write many lines of arithmetic — or you could just call round(number, 2). Predefined functions save time, reduce errors, and make code easier to read.

For this N5 lesson, the required predefined functions are random, round, and length. Python writes these as random.randint(), round(), and len(). SQA pseudocode writes them as RANDOM(), ROUND(), and LENGTH(). The names look slightly different, but the idea is the same: call the function, pass the required parameters, and use the value returned.

Two of these functions are built directly into Python: round() and len(). They can be used straight away. Random number generation is different in Python because it lives inside the random module, so Python programs must include import random before calling random.randint(). In SQA pseudocode, no import line is required.

A predefined function is a "black box" — you pass in arguments, it gives back a value. 3.14159 2 round() rounds to N decimal places 3.14 arguments return value "hello" len() counts characters in a string 5 1 6 random.randint() random integer, inclusive 3 (or 1, 2, 4, 5, or 6) random — different each time Internal code hidden — you only need to know the name, arguments, and return value

Rounding: round()

The round() function rounds a number to a specified number of decimal places.

round(value, decimal_places)

Examples:

  • round(3.14159, 2)3.14
  • round(3.14159, 4)3.1416
  • round(3.7)4 (no second argument — rounds to the nearest whole number)

Rounding is especially important when displaying the result of a division. For example, computing an average often produces many decimal places; round() tidies the output for the user.

In SQA pseudocode this is written as ROUND(value, decimalPlaces) — the same argument pattern, just capitalised.

Length: len()

len(s) returns the number of characters in string s. It counts every character including letters, digits, spaces and punctuation.

  • len("hello")5
  • len("Computing!")10
  • len("N5 CS")5 because the space counts as one character
  • len("")0 (empty string)

A typical use is password validation — checking that a password is at least 8 characters long: if len(password) < 8:. In SQA pseudocode this is written as LENGTH(password).

Random numbers: random.randint()

Python does not include random number generation by default. You must first import the random module at the top of your program, then call random.randint(low, high).

import random

dice = random.randint(1, 6)   # returns 1, 2, 3, 4, 5, or 6
print(dice)

random.randint(low, high) returns a random integer including both endpoints — so random.randint(1, 6) can return 1, 2, 3, 4, 5, or 6 with equal probability.

In SQA pseudocode this is written as RANDOM(low, high). No import line is needed in pseudocode — it is a Python-specific requirement.

The import statement must appear once, at the very top of the program, before any code that uses the module. Forgetting to import is the most common error when using random.randint().

Quick reference

FunctionWhat it returnsPseudocode equivalent
round(x, d)x rounded to d decimal placesROUND(x, d)
len(s)number of characters in string sLENGTH(s)
random.randint(l, h)random integer from l to h inclusiveRANDOM(l, h)

Worked examples

Example 1 — Using round() to tidy an average

Three test scores are 85, 92, and 71. Write a program that calculates the average and displays it rounded to one decimal place.

1
Calculate mentally first: (85 + 92 + 71) ÷ 3 = 248 ÷ 3 = 82.666… — many decimal places, not suitable to display directly.
2
Python code:
score1 = 85
score2 = 92
score3 = 71
average = (score1 + score2 + score3) / 3
average = round(average, 1)
print("Average score:", average)
3
Output: Average score: 82.7round(82.666…, 1) rounds to one decimal place. The second argument to round() is always the number of decimal places required. Note that round() returns the value; we must assign it back to average to store the result.
Example 2 — Using random.randint() for a dice simulation

Write a program that simulates rolling a six-sided die and displays the result.

1
The import random line must come first — before any other code in the file. Without it, Python does not know what random.randint means and will raise a NameError.
2
Python code:
import random

roll = random.randint(1, 6)
print("You rolled:", roll)
3
random.randint(1, 6) returns one of 1, 2, 3, 4, 5, or 6 with equal probability. Both endpoints are included. Each run of the program may give a different result. In SQA pseudocode: SET roll TO RANDOM(1, 6) — no import statement needed in pseudocode.
Example 3 — Writing the same functions in pseudocode

Write SQA pseudocode that generates a random score from 1 to 20, rounds an average to one decimal place, and checks the length of a username.

1
Choose the three predefined functions: RANDOM(1, 20) generates the score, ROUND(average, 1) rounds the average, and LENGTH(username) counts the characters in the username.
2
SQA pseudocode:
SET score TO RANDOM(1, 20)
SET average TO 14.6667
SET roundedAverage TO ROUND(average, 1)
SET username TO "coder42"
SET usernameLength TO LENGTH(username)
SEND score TO DISPLAY
SEND roundedAverage TO DISPLAY
SEND usernameLength TO DISPLAY
3
Trace the fixed values: ROUND(14.6667, 1) gives 14.7. LENGTH("coder42") gives 7. The random score cannot be predicted exactly, but it must be a whole number from 1 to 20 inclusive.
Example 4 — Using len() for password validation

A website requires passwords to be between 8 and 20 characters inclusive. Write a program that checks a stored password against this requirement.

1
len(password) counts every character in the string — letters, digits, symbols, and spaces all count as one character each.
2
Python code:
password = "hello"
length = len(password)
if length < 8 or length > 20:
    print("Invalid — password must be 8 to 20 characters.")
    print("Your password is", length, "characters long.")
else:
    print("Password accepted.")
3
For input "hello": len("hello") = 5. The condition 5 < 8 is true — program prints the rejection message and reports 5 characters. For input "SecurePass1": len("SecurePass1") = 11. The condition is false — program prints Password accepted.
Now you try

A quiz program stores a player's name and three scores. The program should work out the average score rounded to one decimal place, count the number of characters in the player's name, and generate a random bonus score from 1 to 5.

Answer the following:

  1. Which three predefined functions are needed?
  2. Write Python code using the stored values name = "PlayerOne", score1 = 14, score2 = 17, and score3 = 13.
  3. What are the rounded average and name length?
  1. round(), len(), and random.randint().
  2. import random
    
    name = "PlayerOne"
    score1 = 14
    score2 = 17
    score3 = 13
    average = (score1 + score2 + score3) / 3
    average = round(average, 1)
    name_length = len(name)
    bonus = random.randint(1, 5)
    print("Average:", average)
    print("Name length:", name_length)
    print("Bonus:", bonus)
  3. Average = (14 + 17 + 13) ÷ 3 = 44 ÷ 3 = 14.666..., so round(14.666..., 1) gives 14.7. len("PlayerOne") gives 9. The bonus is random, so it could be any whole number from 1 to 5.
Common mistakes
Forgetting to import the random module. Writing roll = random.randint(1, 6) without import random at the top of the file causes a NameError: name 'random' is not defined. The import must appear before any code that uses the module. In pseudocode there is no import, but in Python it is always required.
Reversing the arguments in round(). round(2, 3.14) is wrong — the number to be rounded comes first, the number of decimal places comes second. Always: round(value, decimal_places). The same order applies in SQA pseudocode: ROUND(value, decimalPlaces).
Using the wrong number of parameters. round(3.14159, 2) needs two parameters because it must know both the value and the number of decimal places. len("hello") needs one parameter because it only counts one string. random.randint(1, 6) needs two parameters because it needs a lower and upper limit.
Forgetting that spaces count in length. len("N5 CS") returns 5, not 4, because the space between N5 and CS is a character too. Punctuation and digits also count.
Forgetting to store the return value. round(price, 2) returns a rounded value but does not modify price itself. To update the variable, you must reassign: price = round(price, 2). This applies to all predefined functions — they return a value, they do not change the original variable in place.
Exam tip

The SQA most commonly tests round(), random.randint() / RANDOM(), and len() / LENGTH(). Make sure you know the exact argument order for each: round(value, decimal_places), random.randint(low, high), and len(string) (only one argument).

When a question asks you to "use a predefined function" and gives a context such as "round the result to 2 decimal places", the marker is looking for the correct function call with both arguments in the right order. Showing the correct syntax earns full marks; a vague description of rounding does not.

For random number questions, remember that random.randint(1, 6) includes both endpoints — 1 and 6 are both possible results. If a question says "generate a random number between 1 and 6 inclusive", the arguments are exactly 1 and 6.

In pseudocode questions, predefined functions use the same argument pattern as Python but capitalised: ROUND(result, 2), RANDOM(1, 6), LENGTH(password). No import statement is needed in pseudocode.

Task Set

Questions 1–5 are auto-checked. Questions 6–10 are self-marked — write your answer, then reveal the model answer to check your work.

1. What does round(3.7268, 2) return? TYPE 1

2. Which of the following correctly generates a random integer between 1 and 10 inclusive in Python? TYPE 1

3. What does len("N5 CS") return? TYPE 1

4. What does len("Computing") return? TYPE 1

5. A variable price = 45.6789. Which line correctly rounds it to 2 decimal places and stores the result back in price? TYPE 1

6. Explain what each parameter means in round(12.846, 2), then state the result. TYPE 2

The first parameter, 12.846, is the value being rounded. The second parameter, 2, is the number of decimal places required.

The result is 12.85. To round to 2 decimal places, look at the third decimal digit. In 12.846, the third decimal digit is 6, so the second decimal digit rounds up from 4 to 5.

7. Write the SQA pseudocode for a program that: (a) generates a random integer between 1 and 100, (b) displays the number generated, and (c) displays whether it is above 50, below 50, or exactly 50. TYPE 2

SET number TO RANDOM(1, 100)
SEND "The number generated is " + number TO DISPLAY
IF number > 50 THEN
    SEND "Above 50" TO DISPLAY
ELSE IF number < 50 THEN
    SEND "Below 50" TO DISPLAY
ELSE
    SEND "Exactly 50" TO DISPLAY
END IF

Key points: in SQA pseudocode, RANDOM(1, 100) is used — no import statement is needed. Both endpoints are included so the result can be 1, 2, 3 … 100. The three-way IF/ELSE IF/ELSE handles all possible cases.

8. The code below contains two errors. Identify each error, explain what goes wrong, and write the corrected code.

roll = randint(1, 6)
total = roll + randint(1, 6)
print("Total:", total)
TYPE 2

Error 1 — Missing import statement: The code uses randint but never imports the random module. Python will raise a NameError: name 'randint' is not defined. The fix is to add import random at the top of the file.

Error 2 — Missing module prefix: The function must be called as random.randint(), not randint(). After importing, you must use the full name random.randint() to tell Python which module the function belongs to.

Corrected code:

import random

roll = random.randint(1, 6)
total = roll + random.randint(1, 6)
print("Total:", total)

9. Write a complete Python program that stores two numbers, 7.5 and 4.3, calculates their average, and displays the result rounded to 2 decimal places. The output should be: Average: 5.9 TYPE 3

num1 = 7.5
num2 = 4.3
average = (num1 + num2) / 2
average = round(average, 2)
print("Average:", average)

Trace: average = (7.5 + 4.3) / 2 = 11.8 / 2 = 5.9. round(5.9, 2) = 5.9. Output: Average: 5.9.

10. Write a complete Python program that simulates rolling two six-sided dice. The program should display each dice result, the total, and a message saying "Double!" if both dice show the same number, or "No double." otherwise. TYPE 3

import random

dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
total = dice1 + dice2
print("Dice 1:", dice1)
print("Dice 2:", dice2)
print("Total:", total)
if dice1 == dice2:
    print("Double!")
else:
    print("No double.")

The import random line must appear first. Each call to random.randint(1, 6) is independent and can return any value from 1 to 6 regardless of what the other die showed. The == operator checks whether both dice show the same value.

Teacher notes — Shift+T to hide

Suggested timing: 60 minutes. Warm up 10 min; notes + reference table 15 min; worked examples 15 min; now you try 5 min; task set 15 min.

Key misconception to address: Pupils often remember the function names but mix up the parameters. Keep returning to the pattern: round(value, decimal_places), random.randint(low, high), and len(string).

Live demo suggestion: Open a Python REPL and demonstrate each required function live. Start with 10 / 3 producing a long decimal, then show round(10 / 3, 2) giving 3.33. Then generate several random numbers with random.randint(1, 6) in quick succession to show the randomness. Deliberately trigger the "forgetting to import" error so pupils see exactly what the NameError message looks like — then fix it live. Finish with len("N5 CS") to show that spaces count.

Extension question: Ask pupils to roll a die 6 times using random.randint(1, 6), then display each roll and the rounded average roll. This combines random and round while staying within the required predefined functions.

Note on round() and banker's rounding: Python 3 uses "round half to even" for exact halfway cases, so round(2.5) = 2 and round(3.5) = 4. This is mathematically correct but can surprise pupils who expect .5 always to round up. For N5 exam purposes this detail is not examined — pupils will not encounter exact halfway cases in exam questions. Do not over-explain this unless pupils ask.

SQA command words covered: "state" (Q4), "explain" (Q6, Q8), "write" (Q7 pseudocode, Q9, Q10 Python), "identify" (Q8 errors).