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 Python's built-in functions: round(), abs(), int(), float(), str(), len(), max(), and min()
  • Use random.randint() 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 abs() to find the absolute (positive) value of a number
  • I can use int(), float(), and str() to convert between data types
  • I can use len() to find the number of characters in a string
  • I can use max() and min() to find the largest or smallest of a set of values
  • I can import the random module and use random.randint(low, high) to generate a random integer
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, int(), float(), and str() are examples of what kind of function?

2. A user types 42 at a Python input() prompt. What data type does the program receive?

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.
type conversion
Changing a value from one data type to another. Also called casting. Python's int(), float(), and str() perform type conversion.
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.
absolute value
The distance of a number from zero — always positive. The absolute value of −7 is 7; the absolute value of 7 is also 7. Found using abs().

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.

Python's predefined functions fall into two groups: those built directly into the language (like round(), len(), int()) which are always available, and those in modules (like random.randint()) which must be imported first using an import statement.

Type conversion: int(), float(), str()

These three functions convert a value from one data type to another. This is also called casting.

FunctionPurposeExampleResult
int(x)Converts x to an integer (truncates — does not round)int(3.9)3
int(x)Converts a string of digits to an integerint("42")42
float(x)Converts x to a decimal numberfloat("3.14")3.14
str(x)Converts x to a stringstr(100)"100"

The most common use is wrapping input() to convert user input from a string to a number: age = int(input("Enter your age: ")). Without int(), any arithmetic on age would fail because you cannot add strings to numbers.

Note that int(3.9) gives 3, not 4. int() truncates — it removes the decimal part entirely without rounding. To round to a whole number, use round() instead.

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 nearest integer, returns an int)

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.

Absolute value: abs()

abs(x) returns the absolute value of x — that is, its distance from zero, always positive or zero.

  • abs(-15)15
  • abs(15)15
  • abs(-3.7)3.7

A common use is calculating the difference between two values regardless of which is larger: abs(temp1 - temp2) gives the temperature difference whether temp1 is bigger or smaller.

String length: len()

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

  • len("hello")5
  • len("Computing!")10
  • 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 LEN(string).

Maximum and minimum: max() and min()

max() returns the largest value from a set of arguments; min() returns the smallest.

  • max(34, 17, 28)34
  • min(34, 17, 28)17
  • max(score1, score2, score3) — works with variables too

You can pass two or more arguments. When working with lists (covered in SDD13), you can also pass the list directly: max(scores).

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)
abs(x)absolute value of x (always ≥ 0)ABS(x)
int(x)x as an integer (truncates)INT(x)
float(x)x as a floatFLOAT(x)
str(x)x as a stringSTRING(x)
len(s)number of characters in string sLEN(s)
max(a, b, …)largest of the argumentsMAX(a, b, …)
min(a, b, …)smallest of the argumentsMIN(a, b, …)
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 — Type conversion: float() and str()

A program asks the user for a temperature in Celsius and converts it to Fahrenheit, displaying the result rounded to one decimal place.

1
The formula: Fahrenheit = (Celsius × 9 / 5) + 32. Verified: 0°C → 32°F; 100°C → 212°F.
2
Python code:
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9 / 5) + 32
fahrenheit = round(fahrenheit, 1)
print(str(celsius) + "°C is " + str(fahrenheit) + "°F")
3
Trace for input 100: float("100")100.0. Fahrenheit = (100.0 × 9 / 5) + 32 = 180.0 + 32 = 212.0. round(212.0, 1)212.0. The str() calls convert the numbers to strings so they can be joined with + in the print. Output: 100.0°C is 212.0°F
Example 4 — Using len() for password validation

A website requires passwords to be between 8 and 20 characters inclusive. Write a program that checks whether a password meets 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 = input("Enter a password: ")
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 program asks the user for two integers: a starting balance and a finishing balance for a bank account. The program should display the change in balance (finishing minus starting), the absolute change (always positive, regardless of direction), and whether the balance has increased, decreased, or stayed the same.

Answer the following:

  1. Which predefined function gives you the absolute value of the change?
  2. Write the complete Python code for this program.
  3. What does the program display if the starting balance is 350 and the finishing balance is 200?
  1. abs() — it returns the absolute value of a number, making any negative result positive. abs(200 - 350) = abs(-150) = 150.
  2. start = int(input("Enter starting balance: "))
    finish = int(input("Enter finishing balance: "))
    change = finish - start
    absolute_change = abs(change)
    if change > 0:
        print("Balance increased by £" + str(absolute_change))
    elif change < 0:
        print("Balance decreased by £" + str(absolute_change))
    else:
        print("Balance unchanged.")
  3. change = 200 − 350 = −150. absolute_change = abs(−150) = 150. Since change < 0, the output is: Balance decreased by £150
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).
Confusing int() with round(). int(3.9) gives 3, not 4. int() truncates — it simply removes the decimal part without any rounding. round(3.9) gives 4 because it rounds to the nearest whole number. When an exam question asks you to round, always use round().
Using len() on a number. len(42) causes a TypeErrorlen() only works on strings (and lists, which are covered in SDD13). To find how many digits a number has, first convert it to a string: len(str(42)) returns 2.
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() / LEN(). 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), LEN(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 int(7.9) 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 the difference between int(3.9) and round(3.9). State the result of each and explain why they differ. TYPE 2

int(3.9) returns 3. The int() function truncates — it simply removes the decimal part without any rounding. It does not matter whether the decimal is .1 or .9; it is always removed, giving the integer part only.

round(3.9) returns 4. The round() function rounds to the nearest integer. Since .9 is closer to 1 than to 0, the result rounds up.

They differ because they perform different operations: int() is a type conversion tool that discards the fractional part, while round() is a mathematical rounding function that finds the nearest value at the required precision.

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 asks the user for two numbers (as floats), calculates their average, and displays the result rounded to 2 decimal places. For inputs 7.5 and 4.3, the output should be: Average: 5.9 TYPE 3

num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
average = (num1 + num2) / 2
average = round(average, 2)
print("Average:", average)

Trace for inputs 7.5 and 4.3: average = (7.5 + 4.3) / 2 = 11.8 / 2 = 5.9. round(5.9, 2) = 5.9. Output: Average: 5.9. float(input()) is used so that decimal numbers are accepted; without it, input() returns a string and the division would fail.

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 frequently confuse int() and round(). Reinforce that int() truncates (chops off the decimal) and is primarily a type-conversion tool, while round() is a mathematical rounding function. A useful check: "If you have £3.99, does int(3.99) give the right rounded value?" — no, it gives 3, not 4. round(3.99) gives 4.

Live demo suggestion: Open a Python REPL and demonstrate each function live. Start with 10 / 3 producing a long float, 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.

Extension question: Ask pupils to roll a die 6 times using a FOR loop, storing each result in a separate variable, then use max() and min() to display the highest and lowest roll. This combines random.randint(), a fixed loop (SDD9), and max()/min().

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).