Fundamentals of
Programming
W4 - Functions
1
● Best way to develop and maintain a large program is to
construct it from smaller, more manageable pieces →
divide and conquer.
● Using existing functions as building blocks for creating
new programs is a key aspect of software reusability
○ Allows to execute function from various locations in program just by
calling the function, rather than duplicating the possibly lengthy code
○ Makes programs easier to modify
2
Defining Functions first line in a function’s block
should be a docstring that
briefly explains the function’s
def keyword, followed by the parentheses contain the
purpose
function name (square) function’s parameter list
1. returns control to its
caller
2. gives the result back
to the caller
# 1- Perform a task
# 2- Return a value 3
return
There are two other ways to return control from a function to
its caller:
● Executing a return statement without an expression
terminates the function and implicitly returns the value
None to the caller.
■ None represents the absence of a value.
■ None evaluates to False in conditions.
● NO return statement in a function → implicitly returns the
value None after executing the last statement in the
function’s block.
4
What Happens When You Call a Function
1. The expression square(7) passes the argument 7 to
square’s parameter number.
2. Then square calculates number ** 2 and returns the result.
a. The parameter number
■ exists only during the function call
■ created on each call to the function to receive the argument value
■ destroyed when the function returns its result to the caller.
5
Function’s parameters and variables
● A function’s parameters and variables defined in a
function’s block → all local variables
● Can be used only inside the function and exist only while
the function is executing
○ Trying to access a local variable outside its function’s block causes a
NameError, indicating that the variable is not defined.
6
Accessing a Function’s Docstring via
IPython’s Help Mechanism
7
Functions with Multiple Parameters
8
Python’s Built-In max and min Functions
Using built-in functions or functions from the Python Standard Library’s modules
→ can reduce development time
→ and increase program reliability, portability and performance.
For a list of Python’s built-in functions and modules, see
https://docs.python.org/3/library/index.html
9
Random-Number Generation
random integers in the
range 1–6
10
fig04_01.py
underscore (_) digit
separator
Roll a six-
sided die
6,000,000
times
11
Seeding the Random-Number Generator for
Reproducibility
module’s seed function
to seed the random-
number generator
yourself—this forces
randrange to begin
calculating its
pseudorandom number
sequence from the seed
you specify
12
Case Study: A Game of Chance
13
● Returning multiple
values via a Tuple
● Tuple is an
immutable (that is,
unmodifiable)
sequences of values
● Parentheses are
optional, but we
recommend using
them for clarity
number of variables to the left of = must
match the number of elements in the
tuple; otherwise, a ValueError occurs
14
● The in operator tests
whether the tuple (7, 11)
contains
sum_of_dice’s value
● not in operator to
determine whether a
value is not in an
iterable.
15
Python Standard Library
● A module is a file that groups related functions, data and
classes.
○ every Python source-code (.py) file you create is a module
● A package groups related modules.
A complete list of the standard library modules at
https://docs.python.org/3/library/
16
17
math Module Functions
18
https://docs.python.org/3/library/math.html
19
Using IPython Tab Completion for Discovery
20
Default Parameter Values
use both default params
use the second default
param
not use the default
params
21
Arbitrary Argument Lists
can receive any number
of arguments
22
Passing an Iterable’s Individual Elements as
Function Arguments
* operator, when applied to an iterable argument in a
function call, unpacks its elements
23
Methods: Functions That Belong to Objects
24
Scope Rules
Each identifier has a scope that determines where you can
use it in your program.
● Local Scope
■ A local variable can be used only inside the function that defines it
● Global Scope
■ Identifiers defined outside any function (or class) have global scope—
these may include functions, variables and classes.
25
Accessing a Global Variable from a Function
26
by default, you cannot modify
a global variable in a
function—when you first
assign a value to a variable in
a function’s block, Python
creates a new local variable
27
use global statement to
declare the variable is
defined in global scope
28
Blocks vs. Suites
● Function blocks and control statement suites
● Variable’s scope depends on where the control statement
is defined:
■ If the control statement is in the global scope, then any variables
defined in the control statement have global scope.
■ If the control statement is in a function’s block, then any variables
defined in the control statement have local scope.
29
Shadowing Functions
shadows the built-in function
sum
30
import: A Deeper Look
31
Caution: Avoid Wildcard Imports
32
Binding Names for Modules and Module
Identifiers
33
Passing Arguments to Functions: A
Deeper Look
In many programming languages, there are two ways to pass arguments—pass-by-value
and pass-by-reference (sometimes called call-by-value and call-by-reference,
respectively):
● With pass-by-value, the called function receives a copy of the argument’s value and
works exclusively with that copy. Changes to the function’s copy do not affect the
original variable’s value in the caller.
● With pass-by-reference, the called function can access the argument’s value in the
caller directly and modify the value if it’s mutable.
→ Python arguments are always passed by reference.
When a function call provides an argument, Python copies the argument object’s
reference—not the object itself—into the corresponding parameter
34
Memory Addresses, References and
“Pointers”
● Interact with an object via a reference → object’s address
(or location) in the computer’s memory—sometimes called
a “pointer” in other languages
x contains reference to the object
containing the value 7 x “points to” (that is, references)
the object containing 7
35
Built-In Function id and Object Identities
● No two separate objects can reside at the same address
in memory → every object in memory has a unique
address.
● The integer result of calling id is known as the object’s
identity.
● No two objects in memory can have the same identity.
36
Passing an Object to a Function
the same as that displayed for x previously
=> both the argument x and the parameter
number refer to the same object while cube
executes
37
Testing Object Identities with the is
Operator
is operator returns True if its two operands have
the same identity
38
Immutable Objects as Arguments
immutable (unmodifiable) object—such as an int, float, string or tuple
→ cannot modify the original immutable object’s value
original object, it will
be garbage collected
creates a new object
containing the cubed
value 39
Functional-Style Programming
Python is not a purely functional language. It offers “functional-style”
features that help you write code which is less likely to contain errors,
more concise and easier to read, debug and modify.
40
What vs. How
● Functional-style programming lets you simply say what
you want to do. It hides many details of how to perform
each task.
● external iteration vs internal iteration
● Functional-style programming emphasizes immutability →
avoids operations that modify variables’ values
● Stating what you want done rather than programming
how to do it is known as declarative programming.
41
Pure Functions
● A pure function’s result depends only on the argument(s)
you pass to it
● Does not have side effects → even if you pass a mutable
list to a pure function, the list will contain the same values
before and after the function call
42
Intro to Data Science: Measures of Dispersion
● When talking about a group, the entire group is called the
population
● Selected small subsets of the population known as
samples
● Measures of dispersion (also called measures of
variability) → understand how spread out the values are
43
Using the following population of 10 six-sided die rolls:
population variance = Squaring the difference between each die value and the mean of all
die values
standard deviation = the square root of the variance
Closer the data values are to the mean and the less overall dispersion (that is, spread)
there is between the values and the mean.
44