CMP 4266
Software Development UG1
Lecture – 3
(Based on Gaddis, T., Starting out with Python 3e, Pearson Education)
CMP 4266, School of CS & DT, Birmingham City University.
Outline
Functions
– Introduction
– Benefits of Functions
– Different Types of Functions
– Defining and Calling Function
– Local Variables Vs Global Variables
– Function Arguments
– Functions and Modules
CMP 4266, School of CS & DT, Birmingham City University.
Introduction to Functions
Function: group of statements within a program that perform
as specific task
– Usually one task of a large program
– Functions can be executed in order to perform overall program task
Modularized program: program wherein each task within the
program is in its own function
CMP 4266, School of CS & DT, Birmingham City University.
Using functions to divide and conquer a large task
CMP 4266, School of CS & DT, Birmingham City University.
Benefits of Using Functions
The benefits of using functions include:
– Simpler code
– Code reuse
- write the code once and call it multiple times
– Better testing and debugging
- Can test and debug each function individually
– Faster development
– Easier facilitation of teamwork
- Different team members can write different functions
CMP 4266, School of CS & DT, Birmingham City University.
Different Types of Functions
A void function:
– Simply executes the statements it contains and then terminates.
A value-returning function:
– Executes the statements it contains, and then it returns a value back to
the statement that called it.
- The input, int, and float functions are examples of value-
returning functions.
CMP 4266, School of CS & DT, Birmingham City University.
Defining and Calling a Function
Function definition: specifies what function does
def function_name(parameter1, ……):
statement
statement
return..
Function header: first line of function
– Includes keyword def and function name, followed by parentheses and
colon
Block: set of statements that belong together as a group
– Example: the statements included in a function
– Each block must be indented, i.e. lines in block must begin with the
same number of spaces
- Use tabs or spaces to indent lines in a block, but not both as this
can confuse the Python interpreter
- Spyder IDE automatically indents the lines in a block
CMP 4266, School of CS & DT, Birmingham City University.
Defining and Calling a Function
Functions are given names
– Function naming rules:
- Cannot use key words as a function name
- Cannot contain spaces
- First character must be a letter or underscore
- All other characters must be a letter, number or underscore
- Uppercase and lowercase characters are distinct
Function name should be descriptive of the task carried out by
the function
– Often includes a verb e.g. calculate_average
CMP 4266, School of CS & DT, Birmingham City University.
Defining and Calling a Function
Call a function to execute it. When a function is called:
– Interpreter jumps to the function and executes statements in the block
– Interpreter jumps back to part of program that called the function
- Known as function return
main function: called when the program starts
– Calls other functions when they are needed
– Defines the mainline logic of the program
CMP 4266, School of CS & DT, Birmingham City University.
Defining and Calling Function (Example)
We need to write a program that inputs two numbers from keyboard and
displays the sum of the numbers.
– Apply divide and conquer technique to identify subtasks
- Input number(s)
- Compute Sum
- Display sum
- Implement a function to realize each sub task
- Write a main function to coordinate the functions to achieve the overall task.
- Call main function to execute the program.
CMP 4266, School of CS & DT, Birmingham City University.
Defining and Calling Function (Example)
CMP 4266, School of CS & DT, Birmingham City University.
Defining and Calling Function (Example)
CMP 4266, School of CS & DT, Birmingham City University.
3.1 Exercise - Parameters & passing arguments
(10 minutes)
In-class
Exercise
Develop a basic calculator, which
takes user input, apply
mathematical operators and prints
the result.
For this program develop
– A function that adds 2 user inputs, and
then prints the result.
– A second function that multiplies the
same 2 inputs and prints the result.
CMP4266 , School of CS & DT, Birmingham City University.
Variable Scope and Local Variables
Scope: the part of a program in which a variable may be accessed.
According to scope variable are of two types: local variables and global
variables.
Local variable: variable that is assigned a value inside a function
– The scope of local variable is the function in which it is created
– Belongs to the function in which it was created
- Only statements inside that function can access it, error will occur if
another function tries to access the variable
Different functions may have local variables with the same name
– Each function does not see the other function’s local variables, so no
confusion
CMP 4266, School of CS & DT, Birmingham City University.
Local Variables (Example)
Enter a number :12 First score is : 55
Traceback (most recent call last):
Second score is : 75
File "C:/BCU/Teachin…… main()
File "C:/BCU/Teaching….. main First score is : 55
print("The number is ", n)
NameError: name 'n' is not defined
CMP 4266, School of CS & DT, Birmingham City University.
Global Variables
Global variable: created by assignment statement written
outside all the functions
– Can be accessed by any statement in the program file, including from
within a function
– If a function needs to assign a value to the global variable, the global
variable must be re-declared within the function
- General format: global variable_name
Reasons to avoid using global variables:
– Global variables make debugging difficult
- Many locations in the code could be causing a wrong variable value
– Functions that use global variables are usually dependent on those
variables
- Makes function hard to transfer to another program
– Global variables make a program hard to understand
CMP 4266, School of CS & DT, Birmingham City University.
Global Variables (Example)
Score at beginning : 65 Score at beginning : 65
Score in function : 55 Score in function : 55
Score at end : 65 Score at end : 55
CMP 4266, School of CS & DT, Birmingham City University.
Passing Arguments to Functions
Argument: piece of data that is sent into a function
– Function can use argument in calculations
– When calling the function, the argument is placed in parentheses
following the function name
Parameter variable: variable that is assigned the value of an argument
when the function is called
– Scope of a parameter: the function in which the parameter is used
Arguments are passed by position to corresponding parameters
– First parameter receives value of first argument, second parameter
receives value of second argument, etc.
Changes made to a parameter value within the function do not affect the
arguments
CMP 4266, School of CS & DT, Birmingham City University.
Passing Arguments to Functions
Parameters
Arguments
N before calling sqr function : 5
num1 : 13
num2 : 18 Num before assignment : 5
Sum is : 31 Num after assignment : 7
N after calling sqr function : 5
CMP 4266, School of CS & DT, Birmingham City University.
Keyword Arguments
Keyword argument: argument that specifies which parameter the value
should be passed to
– Position when calling function is irrelevant
– General Format:
function_name(parameter=value)
Possible to mix keyword and positional arguments when calling a function
– Positional arguments must appear first
Example
def compute_interest(principal, rate, period): SyntaxError: non-keyword
interest = principal * rate * period arg after keyword arg
return interest
TypeError: compute_interest() got multiple values for
argument 'rate'
compute_interest(100, 0.7, 6)
compute_interest(rate=0.7, period=6, compute_interest(rate = 0.7, 10, 5)
principal=100)
compute_interest(10, 5, rate = 0.7)
compute_interest(500, period=6, rate=0.7)
CMP 4266, School of CS & DT, Birmingham City University.
Default Parameter Values
Python allows parameter variables of a function to have default values.
– Function can be called with fewer arguments than it is defined, i.e. possible to
skip the parameters that have default value during function call.
Example
def volume(width, height, depth = 2):
return width * height * depth
print(volume(2, 3, 3))
print(volume(2, 3))
– Output
18
12
CMP 4266, School of CS & DT, Birmingham City University.
Returning Multiple Values - A
In Python, a function can return multiple values
– Specified after the return statement separated by commas
- Format: return expression1, expression2, etc.
– When you call such a function in an assignment statement, you need a
separate variable on the left side of the = operator to receive each
returned value
Example
def get_name():
first = input("Enter your first name : ")
last = input("Enter your last name : ")
return first, last
first_name, last_name = get_name()
CMP 4266, School of CS & DT, Birmingham City University.
Returning Multiple Values - B
When a function returns multiple values, simply the function
returns a tuple. For example:
def myfun(a, b, c):
result = myfun(1,2,3)
a = a*2
print(result)
b = b*2
c = c*2
>>>
return a, b, c (2, 4, 6)
>>>
a, b, c = myfun(1, 2, 3)
print(a, b, c)
result = myfun(1,2,3)
print(result[0], result[1], result[2])
>>> >>>
246 246
>>> >>>
CMP 4266, School of CS & DT, Birmingham City University.
3.2 Exercise – Returning Multiple Values
(15 minutes)
In-class
Exercise
Create a function “calculate” that takes three parameters; two
numbers and one string. The string is used to indicate the arithmetic
operation to apply on the two numbers. E.g. to add two numbers you
need to run calculate(2,6, “+”)
The function must use an if statement that uses the sign operator
string to decide on the arithmetic operation to be done on the two
numbers.
The function should returns the answer + an explanation. For
example, running calculate(2, 6, “*” ) should return “multiplying 2
by 6 = 12”
The function “calculate” should be able to call other 4 functions to
perform 4 arithmetic operations , addition, subtraction,
multiplication and division.
CMP4266 , School of CS & DT, Birmingham City University.
Storing Functions in Modules
In large, complex programs, it is important to keep code organized
Modularization: grouping related functions in modules
– Makes program easier to understand, test, and maintain
– Make it easier to reuse code for multiple different programs
Module is a file that contains Python code
– Contains function definition but does not contain calls to the functions
- Importing programs will call the functions
Rules for module names:
– File name should end in .py
– Cannot be the same as a Python keyword
Import module using import statement
import module_name
module_name.function_name
CMP 4266, School of CS & DT, Birmingham City University.
Standard Library Functions and the import Statement
Standard library: library of pre-written functions that comes with Python
– Library functions perform tasks that programmers commonly need
- Example: print, input, range
Some library functions built into Python interpreter
– To use, just call the function
– Can be viewed the list of built-in functions by the command
dir(__builtins__)
– https://docs.python.org/3/library/functions.html
To view standard Python modules visit the following page
– https://docs.python.org/3/tutorial/modules.html
CMP 4266, School of CS & DT, Birmingham City University.