EDA 2425 T03b Functions
EDA 2425 T03b Functions
Luis F. Teixeira
TOPICS OF INTRODUCTION Python Language
TO PROGRAMMING Variables
Operators
Structured programming
Sequence
Selection (if-else)
Repetition (while, for)
Data structures
Functions
Classes
Inheritance
Polymorphism
2
Functions form a fundamental part in the
FUNCTIONS construction of programs in Python
language (classes are the other
fundamental part).
3
FUNCTIONS
def add(x,y):
return x + y
add(3,4)
FUNCTIONS | CALL
def sqr(x):
a 1.2 return x * x
b 1.44
...
a = float(input("Write a number "))
b = sqr (a)
b=sqr(a)
print("The square of", a, "is", b)
...
x 1.2
The function receives variables with values, works with copies
return x*x of the variables (some caution is needed with references!), and
returns another value
6
7
FUNCTIONS | CALL
def sqr(x):
aux = x * x
return aux
FUNCTIONS | CALL
import math The argument can be an
expression
def sqr(x):
return x * x The function can receive the
result of another call to itself
a = float(input("Write a number "))
b = float(input("Write a number "))
Write a number 2
Write a number 3
The square of a+b is 25.0
The eighth power of a+b is 390625.0
The absolute value of a+b is 5.0
8
9
FUNCTIONS | SCOPE
def power (base, n): Variables created in a
i, p = 0, 1
while i < n: function are not accessible
p = p * base outside the function; they
i = i + 1
return p are created when the
function is called and are
i=0;
while i < 10: eliminated when the
print(i, power(2, i)) function ends.
i = i + 1
9
FUNCTIONS | SCOPE
>>> def foo(x):
... print(x)
... x=3
... print(x)
...
>>> x = 5
>>> foo(x)
5
3
>>> x
5
10
FUNCTIONS | SCOPE
>>> x = 5
>>> def foo():
... y=x+1
... x=0
... return y
...
>>> foo()
UnboundLocalError: local variable 'x' referenced before assignment
12
FUNCTIONS | ARGUMENTS
def func(val, first=5, last=7):
return first * val + last
>>> func(2)
17
>>> func(2, first=1, last=1)
3
>>> func(2, 1, 1)
3
>>> func(2, last=5)
15
>>> func(first=7, 1)
SyntaxError: non-keyword arg after keyword arg
13
math
MODULES sqrt
log A module is a file containing Python
cos definitions and statements
…
os
Definitions from a module can be
chdir
open
imported into other modules or into
read
the main module
…
The file name is the module name
myfunc1
mymodule with the suffix .py appended
myfunc2
myfunc3
14
MODULES
def myfunc1():
print("Hello from myfunc1")
mymodule.py
def myfunc2(a,b):
return a+b
import mymodule
mymodule.myfunc1 () main.py
print(mymodule.myfunc2 (5,7))
15
RANDOM NUMBERS
¨ The module random includes some functions to generate
pseudo-random numbers
0.41872335193283494
>>> random.randint(10, 20) int between 10 and 20
18
16
TYPICAL PYTHON FILE
A typical Python file (using only functions) has the structure below.
import module1
import module2
def function1(args1):
...
def function2(args2):
...
def main():
...
if __name__ == "__main__":
main()
17
SPECIAL ATTRIBUTES
18
FUNCTIONS | ITERATIVE VS. RECURSIVE
## iterative implementation
def factorial(x):
ans = 1
for i in range(2, x+1):
ans = ans * i
return ans
19
FUNCTIONS | RECURSION
Recursion is used when a function calls itself, either:
- directly (self-recursion; A calls A),
- indirectly, through the call of other functions
(mutual recursion; for example, A calls B and B calls A).
## recursive implementation
def factorial(x):
if x == 0:
return 1
else:
return x * factorial(x - 1)
20
FUNCTIONS | RECURSION
120
main() factorial(5)
24
factorial(4)
each factorial
6 function has its own
context
factorial(3)
2
factorial(2)
call
1
return
factorial(1)
21
FUNCTIONS | RECURSION
They must have the following characteristics:
the factorial of 1 is 1
1. A simple base case that has the solution and returns a
value (stopping condition). Sometimes, there is more
than one base case!
the factorial of n can
2. A way to bring the problem closer to the base case, be defined from the
i.e., a way to discard part of the problem to obtain a factorial of n-1
simpler problem.
22
FUNCTIONS | RECURSION
The key to thinking recursively is to find the solution to
the problem as a smaller version of the same problem:
Identify the base case(s) and what the base case(s) def factorial(n):
do(es). A base case is the simplest problem that the if n==1:
function can solve. Return the correct value for the
return 1
base case.
else
return n*factorial(n-1)
The recursive function will be reduced to an if-else
condition where the base case returns a value, and
the non-base case recursively calls the same function
with a smaller parameter or dataset.
23
TOWER OF HANOI
The goal is to build a program for this problem:
• three rods designated as L (left), M (middle), and R (right)
• on rod L, several disks of decreasing diameter are stacked
• the goal is to move the disks from L to R, such that, in each move of a disk, a larger
disk is never placed on top of a smaller one.
The ”Tower of Hanoi" problem has an intuitive recursive solution. On the other hand, it
is a problem that does not have an easy iterative solution.
L M R
24
TOWER OF HANOI
The solution can be decomposed in 3 parts
L M R
L M R L M R L M R
move N-1 disks LàM move 1 disk LàR move N-1 disks MàR
recursion 25
TOWER OF HANOI | PYTHON IMPLEMENTATION
# Move 1 disk from the initial rod (ini) to the final rod (fin)
def move_one(ini, fin):
rods = ["left", "middle", "right"]
print(f"Move disk from rod {rods[ini]} to rod {rods[fin]}")
# Main function
if __name__ == "__main__":
n = int(input("How many disks? "))
move(n, 0, 2, 1)
26