Definition
A function is a self-contained, named block of code designed to perform a single, well-defined task. Instead of writing the same logic repeatedly throughout a program, you define it once as a function and then call (invoke) it whenever you need it.
Functions are one of the most important tools for writing clean, maintainable code.
Defining and Calling a Function
DEFINE greet(personName):
PRINT "Hello, " + personName + "!"
greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!
The DEFINE keyword introduces the function. Everything indented beneath it is the function body — the code that runs each time the function is called. The name in brackets (personName) is a parameter.
Parameters and Return Values
Parameters are variables listed in the function definition that receive input values when the function is called. The actual values passed in are called arguments.
Return values are values that the function sends back to the code that called it.
DEFINE add(a, b):
result = a + b
RETURN result
total = add(3, 5) # total is 8
total = add(10, 20) # total is 30
A function does not have to return a value — some functions only perform an action (like printing a message) without producing a result.
The terms "parameter" and "argument" are often used interchangeably in everyday speech, but strictly speaking: a parameter is the variable in the function definition, while an argument is the actual value passed when calling the function.
Why Functions Reduce Repetition
Consider a program that needs to calculate the area of a rectangle in five different places. Without functions:
area1 = 4 * 7
area2 = 10 * 3
area3 = 6 * 6
# ... and so on, with the same formula repeated
With a function:
DEFINE rectangleArea(width, height):
RETURN width * height
area1 = rectangleArea(4, 7)
area2 = rectangleArea(10, 3)
area3 = rectangleArea(6, 6)
Now the formula exists in exactly one place. If you need to change the logic, you change it once and the fix applies everywhere.
This principle — writing each piece of logic only once — is called DRY (Don't Repeat Yourself).
A well-written function should do exactly one thing. If you find yourself naming a function something like calculateAndPrintAndSave, that is a sign it should probably be split into three separate functions.
Practice Problems
What is the difference between a parameter and an argument?
Show answer
What does a return statement do?