Python Functions
Python Functions
Peter Bratby
Functions SKILLPILLS
1. What is a function?
2. Defining and calling functions
3. Importing modules
4. Local variables
5. Function composition
6. Stack Traces
7. Exercises
2
What is a function? SKILLPILLS
3
Example SKILLPILLS
A simple function
def sayhello(name):
print("Hello, " + name)
sayhello("Pete")
4
Defining and calling a function SKILLPILLS
answer = dostuff(1, 2)
comma-separated
function list of arguments
name
5
Execution order: be careful! SKILLPILLS
!!
answer = dostuff(1, 2)
6
Example: cylinder SKILLPILLS
7
Exercise 1 SKILLPILLS
cylinder.py
python console
>>> import cylinder
>>> cylinder.volume(5,10)
785.0
>>> import cylinder as c
>>> c.volume(5,10)
785.0
9
Multiple return statements SKILLPILLS
def oddoreven(x):
if x % 2 == 0:
return "even"
else:
return "odd"
10
Exercise 2 SKILLPILLS
11
Local variables SKILLPILLS
x = 2
print(add3(x))
print(z) error! z does not exist here
12
Local variables SKILLPILLS
def add3(x):
x = x + 3
return x
x = 2 output:
print(add3(x)) 5
?
print(x) ?
2
13
Function composition SKILLPILLS
printblock(2, 3)
output:
***
***
14
Stack trace SKILLPILLS
printblock(3, 0.5)
15
Exercise 3 SKILLPILLS
16
Exercise 4 SKILLPILLS
l = [3, 4, 6, 2, 7]
x = firsteven(l) output:
print(x) 4
17
Exercise 5 SKILLPILLS
18