6.6.2 – Functions, procedures and parameters
Write functions and procedures with and without parameters. Follow arguments and returned values, and place a subprogram’s exit so its whole task finishes.
Functions return a usable value
A function sends a result back to the code that called it. The definition uses def; return supplies the result. Defining it makes it available but does not yet execute its body.
def starting_tokens():
return 10
tokens = starting_tokens()
print(tokens)
This function has no parameters: empty parentheses appear in both the definition and the call. The call returns 10, which the assignment stores. The output is 10. The result could instead be used directly in a larger calculation.
A parameter is a local name in a definition. An argument is the value or variable supplied by a call. Parameters make a function reusable for different data:
def rectangle_area(length, width):
area = length * width
return area
first = rectangle_area(7, 4)
second = rectangle_area(3, 6)
print(first)
print(second)
The first call gives length 7 and width 4; the second uses 3 and 6. Each call runs the calculation with its own parameter values. The outputs are 28 then 18. Argument order matters when the jobs of parameters differ: a discount amount and a starting price are not interchangeable simply because both are numbers.
A function's contract states its inputs and its returned result. For rectangle_area, give valid numeric lengths; the caller receives their product. A temporary local area makes the calculation explicit, but directly returning the product is equally valid.
Procedures perform an action
A procedure performs a task without returning a useful result for the caller. Python still uses def. One procedure can have no parameters; another can receive the data its action needs.
def show_heading():
print("Workshop summary")
def show_progress(name, completed):
print(name + ": " + str(completed))
show_heading()
show_progress("Mira", 7)
Workshop summary
Mira: 7
The first procedure prints a fixed heading; the second adapts its output to two arguments. Parameters do not decide whether a subprogram is a function or a procedure. The difference is the returned result, not the number of inputs or the spelling of def.
| Kind | No parameters | With parameters |
|---|---|---|
| Function | Returns a value without receiving arguments | Returns a result calculated from supplied arguments |
| Procedure | Performs an action without arguments | Performs an action using supplied arguments |
In Python a subprogram that reaches its end without a value-returning statement implicitly returns None. This is useful for diagnosing an accidental assignment from a procedure. It does not turn displayed text into the intended returned result.
def show_double(value):
print(value * 2)
result = show_double(6)
print(result)
12
None
Continue this lesson.
You’re previewing NovaLearn without an account. Create a free account to read the rest.
Create free account