L06 Functions
L06 Functions
Functions
1
Lecture outline
• This lecture introduces functions.
• Formal and actual parameters
• Scope of variables
Our programs so far…
• consisted of a sequence of instructions
• are easy for small-scale problems
• but messy for larger problems
• hard to keep track of details
• difficult to debug large programs
Good programming practice
• Decomposition: divide code into modules
• which are self-contained
• used to break up code
• intended to be reusable
• keep code organized
• keep code coherent
• Abstraction: treat a piece of code as a black box
• do not need to see details
• hide tedious coding details
• Achieve decomposition with functions and abstraction with
function specifications
Functions
• Mathematical functions
• f(x) = x2
• f(x,y) = x2 + y2
• In programming, functions help creating better structure with decomposition
• Functions are not run until they are “called” or “invoked” in a program
• Function characteristics:
• has a name
• has parameters (0 or more)
• has a body
• returns something
Defining and invoking a function
"""
Input: i, a positive int
Returns True if i is even, otherwise False
"""
print("inside is_even")
return i%2 == 0
is_even(3)
Defining and invoking a function
Consider f(x) = x2
>>> 16 # output
Formal and actual parameters
• formal parameter gets bound to the value of the actual parameter
when function is called
• actual parameter is also known as argument
def f(x):
x = x + 1
print('in f(x): x =', x)
return x
x = 3
z = f(x)
Function: Arguments
• Functions may not have arguments and return statement
x = 5
f(x)
print(x)
More examples of variable scope
§ inside a function, can use global variables, but not recommended
def g(y):
print(x)
print(x + 1)
x = 5
g(x)
print(x)
More examples of variable scope
§ inside a function, cannot modify a variable defined outside
def g(y):
x += 1
print(x, y)
x = 5
g(x)
print(x) UnboundLocalError: local variable
'x' referenced before assignment
Exercise
• Write a function to check whether a number is part of Fibonacci
sequence or not.
• Hint:
• You can use another function to generate a Fibonacci Sequence