How to use sub programs (functions and procedures) to produce structured code
2.2.3 Additional Programming Techniques
Practise exam questionsAdditional Programming Techniques — Note 8 of 12
The difference and use of functions and procedures and where to use them effectively
Sub-programs (also called sub-routines) are reusable blocks of code that perform a specific task. There are two types: functions return a value, while procedures perform a task without returning a value. Using sub-programs makes code modular, reusable, and easier to test and maintain.
return keyword.totalPay = calculatePay(experience, miles).greet("Sarah"). A function call is used inside an assignment or expression, because it gives back a value: total = add(5, 3).direction and position are given as parameters, USE them — don't do direction = input() inside the function.return total, not print(total), inside the function.freeseats("Red"), not freeseats(Red). Store the result: redseats = freeseats("Red").result = newPrice(5, "premium") then print(result).totalPay = calculatePay(experience, miles) then print(totalPay).# FUNCTION - returns a value
def newPrice(nights, room):
if room == "basic":
price = 60 * nights
else:
price = 80 * nights
return price # RETURN, not print
# CALLING the function:
result = newPrice(5, "premium")
print(result) # Output: 400
# PROCEDURE - does not return a value
def greet(name):
print("Hello, " + name + "!")
greet("Alice") # Output: Hello, Alice!# Function: returns a value
def add(x, y):
return x + y
total = add(5, 3) # the returned value is stored
print(total) # 8
# Procedure: does a job, returns nothing
def greet(name):
print("Hello", name)
greet("Sarah") # outputs: Hello SarahReady to test yourself?
Practise 2.2.3 questions