2.7 Functions and Procedures
2.7.1 Functions
Functions
Characteristics:
When used: When a value needs to be calculated or reused.
Python example:
- May take parameters
- Must return a value
When used: When a value needs to be calculated or reused.
Python example:
def calculate_total(price, quantity):
return price * quantity
total = calculate_total(5, 4)
print(total)
2.7.2 Procedures
Procedures
Characteristics:
When used: When performing a task such as displaying output.
Python note: In Python, procedures are functions that return no value.
Python example:
- May take parameters
- Must not return a value
When used: When performing a task such as displaying output.
Python note: In Python, procedures are functions that return no value.
Python example:
def greet(name):
print("Hello", name)
greet("Alex")
2.7.3 Sources of functions and procedures
Sources of Code
Functions and procedures can come from:
- User‑written – created by the programmer
- Built‑in – provided by the language (e.g. print, len)
- Standard libraries – included with the language
- Third‑party libraries – supplied externally
numbers = [1, 2, 3]
print(len(numbers))
Python example (library):
import math
print(math.sqrt(16))
2.7.4 Benefits and drawbacks of pre‑written code
Benefits and Drawbacks
Benefits:
- Saves development time
- Often tested and reliable
- Improves code readability
- Less control over implementation
- May include unnecessary features
- Dependency on external updates
2.7.5 Interpreting code using functions and procedures
Interpreting Code
Example:
def add(a, b):
return a + b
result = add(3, 4)
print(result)
This function takes two values, adds them, and outputs the result.
2.7.6 Developing code using functions and procedures
Developing Code
Python example:
def is_even(number):
return number % 2 == 0
num = 6
if is_even(num):
print("Even")
else:
print("Odd")
2.7.7 Debugging code using functions and procedures
Debugging Code
Incorrect code:
def multiply(a, b):
print(a * b)
multiply(2, 3)
Problems:
- Indentation error in function body
def multiply(a, b):
print(a * b)
multiply(2, 3)