Python Functions
CS106AP Lecture 6
Roadmap B asics
in g
Programm The C
onsol Ima
e ges
Day 1!
Graphics Data structures
Midterm
Object-Oriented
Everyday Python
Programming
Life after CS106AP!
Roadmap B asics
in g
Programm The C
onsol Ima
e ges
Day 1!
Python Strings and
Functions the Console
Graphics Data structures
Midterm
Object-Oriented
Everyday Python
Programming
Life after CS106AP!
How do we translate what we know
from Karel into regular Python code?
Today’s How can we make our code more
questions flexible by producing different
outputs depending on the input?
1. Introduction and Review
2. Range For Loops
Today’s 3. Python Functions
topics 4. Variable Scope
5. What’s next?
Who am I?
Sonja
Johnson-Yu
Sonja
Johnson-Yu
Sonja
Johnson-Yu
Sonja
Johnson-Yu
Review
Variables
What is a variable?
A variable is a container for storing a data value.
5
num_flowers = 5
num_flowers
variable’s
name
What is a variable?
A variable is a container for storing a data value.
5
num_flowers = 5
num_flowers
variable’s
value
Terminology summary
● Variables have a name and are associated with a value
● Variable assignment is the process of associating a value
with the name (use the equals sign =)
● Retrieval is the process of getting the value associated
with the name (use the variable’s name)
○ This is how you use variables!
Expressions
Recall: expressions
● The computer evaluates expressions to a single value
● We use operators to combine literals and/or variables into expressions
Arithmetic operators
Operator Precedence
* Multiplication
() 1
/ Division
*, /, //, % 2
// Integer division
+, - 3
% Modulus (remainder)
+ Addition
- Subtraction
Arithmetic operators
Operator Precedence
* Multiplication
() 1
/ Division
*, /, //, % 2
// Integer division
+, - 3
% Modulus (remainder)
+ Addition
Integer division takes the largest integer that is
- Subtraction
equal to or smaller than the quotient
Integer Division Practice!
● 5 + 1 // 2 Integer division takes the
● 9 // 3 largest integer that is equal
to or smaller than the
● 8 // 3
quotient
● -8 // 3
Integer Division Practice!
● 5 + 1 // 2 = 5 Integer division takes the
● 9 // 3 = 3 largest integer that is equal
to or smaller than the
● 8 // 3 = 2
quotient
● -8 // 3 = -3
How can I repeat a task a finite
number of times?
While loop with variables
counter = 0 WARNING: do not use
while counter < 3: variables on Karel!
do_something()
counter += 1
While loop with variables
counter = 0
while counter < 3:
do_something()
counter += 1
This is the same thing as:
counter = counter + 1
While loop with variables
counter = 0
while counter < 3:
do_something()
counter += 1
Generally, x += y is the same as:
x = x + y
While loop with variables
counter = 0
while counter < 3:
do_something()
counter += 1
Generally, x += y is the same as:
x = x + y
You can also do: -=, *=, /=
While loop with variables
counter = 0
while counter < 3: Computer scientists count from 0.
do_something()
counter += 1
While loop with variables
counter = 0
while counter < 3:
do_something()
counter += 1
counter
0
While loop with variables
counter = 0
while counter < 3:
do_something()
counter += 1
counter
0
While loop with variables
counter = 0
while counter < 3: True
do_something()
counter += 1
counter
0
While loop with variables
counter = 0
while counter < 3: True
do_something()
counter += 1
counter
1
While loop with variables
counter = 0
while counter < 3: True
do_something()
counter += 1
counter
2
While loop with variables
counter = 0
while counter < 3:
do_something()
counter += 1
counter
3
While loop with variables
counter = 0
while counter < 3: False!
do_something()
counter += 1
counter
3
For loops
For loop with range
for i in range(3):
do_something()
For loop with range
for i in range(3): Definition
do_something()
for loop
A way to repeat a block of
code a specific number of
times
For loop with range
for i in range(3):
do_something()
Tells us we’re going to loop through one by one
For loop with range
for i in range(3):
do_something()
A variable that helps us keep track of
where we are (index)
For loop with range
for i in range(3):
do_something()
Number of iterations
For loop with range
for i in range(3):
do_something()
Can be a variable, as long as it’s an int!
For loop with range
for i in range(3):
do_something()
Built-in function
Range
range(3) -> iterates through 0,1,2
Range
range(3) -> iterates through 0,1,2
range(0, 3) -> iterates through 0,1,2
Range
range(3) -> iterates through 0,1,2
range(0, 3) -> iterates through 0,1,2
range(4, 7) -> iterates through 4,5,6
Range
for i in range(end_index):
# assumes 0 is the start index
Range
for i in range(end_index):
# assumes 0 is the start index
for i in range(start_index, end_index):
# end_index is not inclusive!
# recall: range(4,7) -> 4,5,6
How can I make my code more
flexible?
Python Functions
print(x) i s _ cl e a r()
front_
_ ri g ht()
tu r n
math.sqrt(4)
average(x, y) r e ()
t u
m pera
d i c t_te
pre
Karel Functions
def turn_right():
turn_left()
turn_left()
turn_left()
Karel Functions
def move_x_times():
# ????
Karel Functions
def move_x_times():
# ????
How can we make functions more flexible and
reusable by producing different outputs?
Function Analogy
toaster()
Slide adapted from Chris Piech
Function Analogy
toaster(bread)
bread
Slide adapted from Chris Piech
Function Analogy
toaster(bread)
bread toast
Slide adapted from Chris Piech
Function Analogy
toaster(bagel)
bagel
Slide adapted from Chris Piech
Function Analogy
toaster(bagel)
bagel
You don’t need a different toaster for toasting bagels! Use the same one.
Slide adapted from Chris Piech
Function Analogy
toaster(bagel)
bagel toasted
bagel
Slide adapted from Chris Piech
Anatomy of a Function
input function(input) output
parameter(s) “return value”
/arguments
Anatomy of a Function
def function_name(param1, param2):
result = # do something
return result
Anatomy of a Function
def function_name(param1, param2):
result = # do something
return result
function
definition
Anatomy of a Function
def function_name(param1, param2):
result = # do something
return result name
Anatomy of a Function
def function_name(param1, param2):
result = # do something
return result input expected
Anatomy of a Function
def function_name(param1, param2):
result = # do something
return result parameters
Anatomy of a Function
def function_name(param1, param2):
result = # do something
Definition
return result
parameter(s)
One or more
variables that a
function expects as
input
Anatomy of a Function
def function_name(param1, param2):
result = # do something
return result
output expected
Anatomy of a Function
def function_name(param1, param2):
result = # do something
return result
return value
Think/Pair/Share:
Find the function definition, function
name, parameter(s), and return value.
Anatomy of a Function Think/Pair/Share:
def main(): Find the function
mid = average(10.6, 7.2) definition, function name,
print(mid) parameter(s), and return
value in average.
def average(a, b):
sum = a + b
return sum / 2
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
print(mid)
def average(a, b):
sum = a + b
return sum / 2
function
definition
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
print(mid)
def average(a, b):
sum = a + b
name
return sum / 2
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
print(mid)
def average(a, b):
sum = a + b
return sum / 2
parameters
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
print(mid)
def average(a, b):
sum = a + b
return sum / 2
parameters
return value
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
Definition
print(mid)
Return value
Value that a function
def average(a, b): hands back to the
sum = a + b
return sum / 2 “calling” function
return value
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
Definition
print(mid)
Return value
Value that a function
def average(a, b): hands back to the
sum = a + b
return sum / 2 “calling” function
return value What is the “calling” function?
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
print(mid)
caller
def average(a, b): (calling function)
sum = a + b
return sum / 2
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
print(mid)
caller
def average(a, b): (calling function)
sum = a + b
return sum / 2
callee
(called function)
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
print(mid)
function “call”
def average(a, b):
sum = a + b
return sum / 2
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
print(mid)
arguments
def average(a, b):
sum = a + b
return sum / 2
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
print(mid)
arguments
def average(a, b):
sum = a + b
return sum / 2 What’s the difference between
arguments and parameters?
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
print(mid)
def average(a, b):
sum = a + b
return sum / 2
parameters are the name of input
values in the function definition
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
print(mid)
arguments are the values passed
def average(a, b): in when function is called!
sum = a + b
return sum / 2
Anatomy of a Function
def main():
mid = average(10.6, 7.2)
print(mid) Note that we’re storing the
returned value in a variable!
def average(a, b):
sum = a + b
return sum / 2
Recall from last lecture:
>>> math.sqrt(4)
2.0
Function
Recall from last lecture:
>>> math.sqrt(4)
2.0
Argument
Recall from last lecture:
>>> math.sqrt(4)
2.0
Return value
Anatomy of a Function
4 math.sqrt(4) 2.0
argument return value
Think/Pair/Share:
Write a function that takes in two
values and outputs the sum of their
squares.
Think/Pair/Share:
Write a function that takes in two
values and outputs the sum of their
squares. [demo]
Functions as Python Objects
def add(x, y):
return x + y add function
object
Parameters and return values are optional
def turn_right():
turn_left()
turn_left()
turn_left()
“I’m a function too!”
Parameters and return values are optional
def turn_right():
turn_left()
turn_left() no parameters
turn_left()
“I’m a function too!”
Parameters and return values are optional
def turn_right():
turn_left()
turn_left()
turn_left()
“I’m a function too!”
no return value
When am I allowed to use a
variable?
Scope
Scope Variable Life Expectancy
Definition
scope
The parts of a program where you can access
a variable
Variable Scope
def main():
function_name()
print(y)
def function_name():
x = 2
y = 3 this is the scope
where x and y “live”
Variable Scope
def main():
function_name()
print(y)
def function_name():
x = 2
y = 3
Variable Scope
def main():
function_name()
print(y)
def function_name():
x = 2
y = 3
Variable Scope
def main():
function_name()
print(y)
x
2
def function_name():
x = 2
y = 3
Variable Scope
def main():
function_name()
print(y)
x
2
def function_name():
x = 2
y = 3 y
3
Variable Scope
def main():
function_name()
print(y)
def function_name():
x = 2
y = 3
Variable Scope
def main():
function_name()
print(y)
NameError
def function_name():
x = 2
y = 3
Variable Scope
def main():
function_name()
print(y)
y is now out of scope!
def function_name():
x = 2
y = 3
Variable Scope
def main():
function_name()
print(y)
y is now out of scope!
def function_name():
x = 2
y = 3
Once a function finishes executing, the
variables declared inside of it are no
longer accessible!
Unless...
def main():
y = function_name()
print(y)
def function_name():
x = 2
y = 3
return y
Unless...
def main():
y = function_name()
print(y)
if we return y, we
def function_name(): can use it in main()
x = 2
y = 3
return y
Let’s put it all together!
Receipt program
● What subtasks can we break this program into?
Receipt program
● What subtasks can we break this program into?
○ calculating tax
○ calculating the tip
○ aggregating tax and tip
[demo]
How do we translate what we know
from Karel into regular Python code?
Today’s How can we make our code more
questions flexible by producing different
outputs depending on the input?
What’s next?
Tomorrow: making programs interactive!
● Strings: representations of text
● Interactive programs
Roadmap B asics
in g
Programm The C
onsol Ima
e ges
Day 1!
Python Strings and
Functions the Console
Graphics Data structures
Midterm
Object-Oriented
Everyday Python
Programming
Life after CS106AP!