04 Functions
04 Functions
CS115
INTRODUCTION TO PROGRAMMING IN PYTHON
WEEK 4
What are Functions
A group of related statements that performs a specific task.
Help divide a program into smaller and modular chunks.
As the size of a program grows, functions make it more organized and manageable.
Using functions minimizes repetition and makes the code reusable.
Functions are not executed in a program until they are “called” or “invoked”
2
Why do we use Functions?
Abstraction:
• a process of handling complexity by hiding unnecessary information from the
use
Reusability:
• the measurement of the likelihood that a given unit of code can be successfully
incorporated into another program. Code reuse allows programmers to reuse
the same code for similar features in multiple apps, reducing the time it takes to
develop new applications.
Modularity:
• separating a program's functions into independent pieces or building blocks,
each containing all the parts needed to execute a single aspect of the
functionality.
3
How to draw this shape?
I. Lines between coordinates. II. Moving pen from a start point. Drawing regular shapes
(x2, y2)
Turn angle x
(x3, y3)
(x1, y1) (x1, y1)
def draw_roof():
def draw_rect(): draw_triangle()
______
______ def draw_house():
draw_flat()
draw_roof()
Reusing code in different places
Functions
def draw_triangle():
______
______
def draw_rect():
______
______
def draw_flat():
def draw_house(): def draw_apartment_3(): def draw_apartment_5():
draw_rect()
draw_flat() draw_flat() draw_flat()
def draw_roof(): draw_roof() draw_flat() draw_flat()
draw_triangle() draw_flat() draw_flat()
draw_roof() draw_flat()
draw_flat()
draw_roof()
Assume drawings are from ground to upwards
apartment_3()
vs
…
apartment(2) apartment(5)
apartment_5() apartment(3)
Let’s make it parametric.
Functions Assume that the drawings are from ground to upwards draw_apartment(1)
def draw_triangle():
______
______
draw_apartment(2)
def draw_rectangle():
______
flat_count ?
______
def draw_flat():
draw_rect()
def draw_apartment(flat_count):
def draw_roof(): for i in range(flat_count): draw_apartment(3)
draw_triangle()
draw_flat()
draw_roof()
draw_castle_2() draw_castle_2()
draw_apartment_3() draw_apartment(3)
move to right move to right
draw_apartment_2() draw_apartment(2)
move to right move to right
draw_house() draw_apartment(1)
move to right move to right
draw_apartment_2() draw_apartment(2)
move to right move to right
draw_apartment_3() vs draw_apartment(3)
draw_apartment_3() draw_apartment()
draw_apartment_2()
draw_house()
Abstraction, Reusability, Modularity
draw_triangle()
or
draw_roof()
draw_rect()
or
draw_flat()
draw_street_view()
draw_house()
draw_apartment(flat_count)
draw_castle() draw_church()
12
We can deal with more complex and higher level structures or
problems
Defining Functions - Syntax
def function_name( formal_parameter_list ):
"""
docstring comment
"""
statements
return
15
Calling Functions
Once function is defined, it can be called from the script or from another function.
The function header is a contract that defines the name of the function and the
data/parameters required by the function.
16
return Statement
return only has meaning inside a function
Statement can contain an expression that is evaluated, and the value is
returned.
If no return statement present, the function returns None, a NoneType
object.
Only one return statement can be executed.
When the return statement is executed, function exits and returns to
calling location.
Any code in the function after the return statement will not be executed.
17
One Warning: If NO return STATEMENT
Python returns the value None, if no return given
None is of type NoneValue and represents the absence of a value.
def is_even_one(val):
if val % 2 == 0:
print('number is even')
else:
print('number is odd')
def is_even_two(val):
if val % 2 == 0: Output:
return True
number is even
r1 = is_even_one(4) Value: None Type: <class 'NoneType'>
print('Value: ', r1, 'Type: ', type(r1))
r2 = is_even_two(4) Value: True Type: <class 'bool'>
print('Value: ', r2, 'Type: ', type(r2))
r3 = is_even_two(5) Value: None Type: <class 'NoneType'>
print('Value: ', r3, 'Type: ', type(r3))
18
Variable Scope and Functions
The formal parameters will be assigned the values passed in the function call, the actual
parameters.
New scope/frame/environment is created when a function is entered.
19
Visualizing Variable Scope
def f( x ): GLOBAL SCOPE
x = x + 1
f some code
print( 'in f(x): x =', x )
return x x 3
x = 3 z
z = f( x )
20
Visualizing Variable Scope
def f( x ): GLOBAL scope f scope
x = x + 1
f some code x 3
print( 'in f(x): x =', x )
return x x 3 x
x = 3 z z
z = f( x )
21
Visualizing Variable Scope
def f( x ): GLOBAL scope f scope
x = x + 1
f some code x 4
print( 'in f(x): x =', x )
return x x 3 x
x = 3 z z
z = f( x )
22
Visualizing Variable Scope
def f( x ): GLOBAL scope f scope
x = x + 1
f some code x 4
print( 'in f(x): x =', x )
return x x 3 x
x = 3 z z
z = f( x )
Output:
in f(x): x = 4
23
Visualizing Variable Scope
def f( x ): GLOBAL scope f scope
x = x + 1
f some code x 4
print( 'in f(x): x =', x )
return x x 3 x
x = 3 z z
z = f( x )
Output:
4
24
Visualizing Variable Scope
def f( x ): GLOBAL scope
x = x + 1
f some code
print( 'in f(x): x =', x )
return x x 3
x = 3 z 4
z = f( x )
Output:
4
25
Exercises:
1. Write a function that returns the sum of the digits of a positive integer. Use this function to find the sum
of digits of the positive numbers input by the user.
◦ See: 04_exercise1.py
2. Write a function that takes a number as a parameter and returns the reverse of the number.
◦ See: 04_exercise2.py
3. Write a function that converts a given string s of a binary number in base 2 to its decimal equivalent and
returns the decimal value.
◦ First write a function, named is_binary, that that takes a string parameter and returns True if the
parameter string is a binary string with 0s and 1s (e.g., ‘101’), False otherwise (e.g., ‘123’).
◦ Then write a function, named convert_to_decimal, that takes a string parameter and uses your
is_binary function to check if the parameter string is a binary number. If it is a binary, then your
function converts it to its equivalent decimal. Else it displays an appropriate message to indicate that it
is not a valid string for a binary number.
See: 04_exercise3.py
26
Variable Scope
The scope of a variable is the part of the program from which the variable can be accessed.
Local variables are variables that are defined within a function.
Local variables become available from the point that they are defined in a function until the end
of the function in which it they are defined.
Global variables are that are defined outside of functions and have a global scope. Global
variables are visible/accessible from inside functions; however, they cannot be directly updated.
27
SCOPE EXAMPLE
Inside a function, can access a variable defined outside.
Inside a function, cannot modify a variable defined outside unless you use the global keyword which is not
recommended.
Output: Output:
2 5
5 6
5
28
Global Variables
Variables that are defined outside of functions.
A global variables are visible from within all functions.
Any function that wants to update a global variable must include a global declaration.
Variables that are assigned values/updated inside functions, with the same name as global
variables, are local variables.
If a variable in a function is declared using the global keyword it references the global
variable and can be used to access/update the global variable from inside the function.
Warning: Accessing/updating global variables in functions is not generally recommended, as
it violates the principle of modularity. Global variables access from within functions can cause
unexpected results.
29
Global Variables - Example
def f(): def g() :
x = 1 global x
print(x) x = 1
print(x)
x = 5
f() x = 5
print(x) g()
print(x)
Output: Output:
1 1
5 1
30
Summary – when a function is called:
1) Actual parameters are evaluated, formal parameters are bound to the values of the
actual parameters.
2) Point of execution (control) moves from the calling statement to the first statement
inside the function.
3) Code in the (indented) body of the function is executed until either:
◦ return statements is reached, and the value following the return
statement is returned.
◦ End of the body of the function reached, None is returned.
4) The point of execution is transferred back to the code following the invocation.
31
Keyword Arguments
Positional arguments: actual parameters are bound to formal parameters in the
order which they are passed. Ex. first formal parameter is bound to the first actual
parameter, the second to the second, etc.
Keyword arguments: formal parameters are bound to actual parameters using the
name of the formal parameter in the calling statement.
32
Keyword Arguments
def printName(firstName, lastName, reverse):
if reverse:
print(lastName + ',' + firstName)
else:
print(firstName, lastName)
The statements above are equivalent, all call printName with the same actual parameter values.
Keyword arguments can appear in any order
Non-keyword arguments cannot follow a keyword arguments, the following is not allowed.
printName('Joe', lastName='Smith', False)
33
Default Parameters
Default values indicate that the function argument will take that value if no
argument value is passed during the function call.
The default value is assigned by using the assignment(=) operator of the for:
keywordname = value
Parameters without a default value are required.
Parameters with a default value are optional.
You provide preferred, default values for your parameters. You let users of
your method change those values for their own needs.
34
Default Parameters
Keyword arguments can be used together with default parameter values.
def printName(firstName, lastName, reverse = False):
if reverse:
print(lastName + ',' + firstName)
else:
print(firstName, lastName)
35
Functions as Objects
In Python, a function can be assigned to a variable. This assignment does not call the function,
instead a reference to that function is created.
my_fun = round( 3.48 ) # this statement calls or invokes the round function;
# my_fun is assigned the value returned by the function
36
Higher Order Functions
A function is called Higher Order Function if it contains other functions as a
parameter or returns a function as an output.
Properties of higher-order functions:
A function is an instance of the Object type.
You can store the function in a variable.
You can pass the function as a parameter to another function.
You can return the function from a function.
You can store them in data structures such as hash tables, lists, …
37
A Simple Example – what is the output?
def do_this( num, this ):
return this(num)
38
A Simple Example – what is the output?
def do_this( num, this ): Output:
return this(num) Enter a number: 62.364
Ceiling of 62.364 is 63
val = float(input('Enter a number: ')) int representation of 62.364 is 62
Rounded square root of 62.364 is 8
# do this - find the ceiling of the value
See: 05_higher_order_functions01.py
result = do_this(val, math.ceil)
print(f'Ceiling of {val} is {result}')
39
A Simple Example – returning functions
def find_function( choice ):
if choice == 1:
return int
elif choice == 2:
return float
else:
return bool
40
Trace the following program and find the output:
def f(x):
def g(): Visualization of this code in
x = 'abc'
print('x = ', x) pythontutor.com
def h():
z = x
print('z = ', z)
x = x + 1
print('x = ', x)
h()
g()
print('x = ', x)
return g
x = 3
z = f(x)
print('x = ', x)
print('z = ', z)
z()
41
Trace the following program and find the output:
def f(x):
def g():
x = 'abc'
print('x = ', x)
def h():
z = x Output:
print('z = ', z) x = 4
z = 4
x = x + 1 x = abc
print('x = ', x) x = 4
h() x = 3
g() z = <function f.<locals>.g at 0x0000027C3EC98400>
print('x = ', x) x = abc
return g
x = 3
z = f(x)
print('x = ', x)
print('z = ', z)
z()
42
Terms of Use
⮚ This presentation was adapted from lecture materials provided in MIT Introduction
to Computer Science and Programming in Python.
⮚ Licenced under terms of Creative Commons License.
43