03 Functions Part1
03 Functions Part1
u Reading:
u Textbook: 5.1 – 5.8
u Learning Objectives: (You should be able to…)
u perform a complete function design, including documentation and test cases
u pass arguments to a function
u return values from a function
u differentiate between local and global variables
u identify the scope of a variable
2
What we know already…
3
Local variables and scope
u A variable’s scope are the parts of the program in which the variable
can be accessed
u for a local variable: its scope begins when the variable is assigned, and
continues through to the end of its indented section
u variable-scope.py
4
variable-scope.py
def fn1():
x = 5
scope of x (it can only be accessed in fn1()
print(x)
def fn2():
print(x)
def main():
fn1()
fn2()
5
variable-scope.py
def fn1():
x = 5
print(x)
fn1() has a local variable x
def fn2():
fn2() has a local variable x, which is
x = 3
handled completely independently from the
print(x) x in fn1()
def main():
fn1() neither x can be accessed from main
fn2()
6
Sharing information across functions
u Terminology is confusing:
u from the point of view of the function call, these are called arguments
u from the point of view of the function definition, they are called parameters
7
Defining functions that take a parameter
8
Parameter passing and scope
def do_some_math(x):
y = 3
if (x < y): scope of x and y
z = 2 * x is the whole
scope of z
print("z is:", z) function body
print("done")
9
Parameter Passing complexities
10
This can get complicated!
11
Steps in a complete function design
1. Signature:
u The number and types of the arguments passed to the function
2. Purpose:
u A short explanation of what the function does
3. Examples/Tests:
u Provide some example values that we would call the function with…
u … and what you expect the function to produce given these values
4. Definition
u write the function definition so work as intended
5. Verification
u Run your code and ensure the examples produce the results you intended
12
Complete function design example
# (int -> None)
1.Signature
# prints out double the given number
def double(num): 2.Purpose
print(num*2)
3.Tests
def main(): 4.Definition
double(3) # expects 6
double(7) # expects 14 5.Then run it!
main()