GET214: COMPUTING AND SOFTWARE ENGINEERING
(Programming in Python)
LESSON 7: PYTHON FUNCTIONS
Learning Outcomes:
At the end of the lesson, students should be able to:
1. Identify function calls in a program
2. Describe benefits of using functions
3. Identify control flow and describe how it moves between statements and
function calls
4. Identify function arguments and parameters
5. Identify and employ function’s return values
6. Describe the difference between positional and keyword arguments
7.1 Introduction to functions
Functions are the next step toward creating optimized code as a software developer.
If the same block of code is reused repeatedly, a function allows the programmer to
write the block of code once, name the block, and use the code as many times as
needed by calling the block by name. Functions can read in values and return values
to perform tasks, including complex calculations.
7.2 Calling a Function
A function is a named, reusable block of code that performs a task when called.
Throughout the book, functions have been called to perform tasks. Examples: print()
prints values, and sqrt() calculates the square root.
7.3 Defining a Function
A function is defined using the def keyword. The first line contains def followed by
the function name (in snake case), parentheses (with any parameters—discussed
later), and a colon. The indented body begins with a documentation string describing
the function's task and contains the function statements. A function must be defined
before the function is called.
7.4 Benefits of using functions
A function promotes modularity by putting code statements related to a single task
in a separate group. The body of a function can be executed repeatedly with multiple
function calls, so a function promotes reusability. Modular, reusable code is easier
to modify and is shareable among programmers to avoid reinventing the wheel.
Example 7.1: Greet function
1
(i) Define a function greet that takes the name of a person as arguments and
prints a welcome message.
(ii) Write a for loop that populates a list with 5 names of persons to be greeted.
(iii) Loop through the names entered in (ii) above and in each iteration, call the
greet function with the name from the list.
#function definition
def greet(name):
"""This program gets name as argument and displays
welcome message
"""
print(f"Welcome {name}. It's good to see you")
#populate the names
names = []
for i in range(5):
name = input(f"Enter name number {i+1}: ")
[Link](name)
#print and empty line
print()
#function call
for person in names:
greet(person)
Sample output
2
7.5 Control Flow and Functions
Control flow is the sequence of program execution. A program's control flow begins
at the main program but rarely follows a strict sequence. For example, control flow
skips over lines when a conditional statement isn't executed. When execution reaches
a function call, control flow moves to where the function is defined and executes the
function statements. Then, control flow moves back to where the function was called
and continues the sequence.
7.6 Function arguments and Parameters
What if a programmer wants to write a function that prints the contents of a list?
Good practice is to pass values directly to a function rather than relying on global
variables. A function argument is a value passed as input during a function call. A
function parameter is a variable representing the input in the function definition.
Note: The terms "argument" and "parameter" are sometimes used interchangeably
in conversation and documentation.
7.7 Multiple arguments and Parameters
Functions can have multiple parameters. For example, a function uses two
parameters, length and width, to compute the square footage of a room. Function
calls must use the correct order and number of arguments to avoid undesired
behavior and errors (unless using optional or keyword arguments as discussed later).
Example 7.2: Area of a Triangle
The area of a triangle, given the 3 sides a, b & c is given as follows:
𝐴𝑟𝑒𝑎 = √𝑠(𝑠 − 𝑎)(𝑠 − 𝑏)(𝑠 − 𝑐)
Where s is the semi perimeter and is given by:
𝑎+𝑏+𝑐
𝑠=
2
The following code defines and calls the area function
3
7.8 Returning from a function
When a function finishes, the function returns and provides a result to the calling
code. A return statement finishes the function execution and can specify a value to
return to the function's caller. In the last example, a floating point value representing
the area of the triangle is returned to the caller. There are some functions that have
no return statement, which is the same as returning None, representing no value.
Example 7.3: Quadratic Equation Function
The quadratic equation 𝑎𝑥 2 + 𝑏𝑥 + 𝑐 = 0 has the solution:
−𝑏 + √𝑏 2 − 4𝑎𝑐
𝑥1 =
2𝑎
−𝑏 − √𝑏 2 − 4𝑎𝑐
𝑥2 =
2𝑎
Write a python function quard_eqn() that takes a, b and c as parameters and returns
a tuple of x1 and x2.
4
Example 7.4: Function to generate the multiplication table of any number
5
Activity 7.1: Estimated days alive
7.9 Keyword Arguments
So far, functions have been called using positional arguments, which are arguments
that are assigned to parameters in order. Python also allows keyword arguments,
which are arguments that use parameter names to assign values rather than order.
When mixing positional and keyword arguments, positional arguments must come
first in the correct order, before any keyword arguments.
For instance, with reference to example 7.3, given that a = 1, b = -1, c= -20, calling
the function as quard_eqn(a,b,c) will produce same result as calling it as
quard_eqn(c=-20, a=1, b=-1)
The first is called positional arguments while the latter is called keyword arguments.
7.10 Default Parameters
Functions can define default parameter values to use if a positional or keyword
argument is not provided for the parameter.
Example: def season(m, d, hemi="N"): defines a default value of "N" for
the hemi parameter.
Note: Default parameter values are only defined once to be used by the function, so
mutable objects (such as lists) should not be used as default values.
6
Activity 7.2: Stream Donation