8 PythonFunctions
8 PythonFunctions
Adopted from Stanford Uni’s CS106ap course slides by Kylie Jue and Sonja Johnson-Yu
How do we translate what we know
from Karel into regular Python
Today’s code?
5. What’s next?
Review
Variables
What is a variable?
num_flowers = 5
num_flowers
5
variable’s
name
What is a variable?
num_flowers = 5
num_flowers
5
variable’s
value
Terminology summary
+ Addition
- Subtraction
Arithmetic operators
Operator Precedence
* Multiplication
() 1
/ Division
*, /, //, % 2
// Integer division
+, - 3
% Modulus (remainder)
● 5 + 1 // 2 Integer division
● 9 // 3 takes the largest
integer that is equal
● 8 // 3
to or smaller than
● -8 // 3 the quotient
Integer Division Practice!
● 5 + 1 // 2 = 5 Integer division
● 9 // 3 = 3 takes the largest
integer that is equal
● 8 // 3 = 2
to or smaller than
● -8 // 3 = -3 the quotient
Repetition
For each loops
For each loops
A new type of for
loop!
Recall: For range() loops
for i in range(end_index):
# assumes 0 is the start index
do_something()
(start_index, end_index,
step)
Advanced For Range Loops
>>> for i in range(4, 0, -1):
... print(i)
(start_index, end_index,
step)
Advanced For Range Loops
>>> for i in range(4, 0, -1):
... print(i)
4
(start_index, end_index,
step)
3
1
Advanced For Range Loops
>>> for i in range(0, 8, 2):
Advanced For Range Loops
>>> for i in range(0, 8, 2):
... print(i)
Advanced For Range Loops
>>> for i in range(0, 8, 2):
... print(i)
6
For loop with range
for i in range(3):
do_something()
For loop with range
for i in range(3):
do_something()
for i in range(3):
do_something()
for i in range(3):
do_something()
Number of iterations
For loop with range
for i in range(3):
do_something()
for i in range(3):
do_something()
Built-in
function
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
• Two parts:
• General format:
while condition:
statements
While loop with variables
counter = 0
while counter < 3:
do_something()
counter += 1
counter = 0
while counter < 3:
do_something()
counter += 1
counter = 0
while counter < 3:
do_something()
counter += 1
counter = 0
while counter < 3:
do_something()
Computer scientists count
counter += 1 from 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:
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
How can I write shorter code?
The Augmented Assignment Operators
• In many assignment statements, the variable on the left side of the =
operator also appears on the right side of the = operator
• Augmented assignment operators: special set of operators designed for
this type of job
• Shorthand operators
The Augmented Assignment Operators (cont’d.)
How can a user signal the end of a repetition?
Sentinels
• Sentinel: special value that marks the end of a sequence of items
n _ r i g h t()
tur math.sqrt(4)
average(x, y) r e ()
a tu
t_ te mper
d i c
pre
Karel Functions
def turn_right():
turn_left()
turn_left()
turn_left()
Karel Functions
def move_x_times():
# ????
Karel Functions
def move_x_times():
# ????
toaster()
toaster(bread)
bread
toaster(bread)
bread toast
toaster(bagel)
bagel
toaster(bagel)
bagel
toaster(bagel)
bagel toasted
bagel
parameter(s)/ “return
arguments value”
Functions as Python Objects
“I’m a function
notoo!”
return
value
Value-Returning Functions
• void function: group of statements within a program for performing a
specific task
• Call function when you need to perform the task
• Value-returning function: similar to void function, returns a value
• Value returned to part of program that called the function when function finishes executing
Defining and Calling a Function (cont’d.)
• Function name should be descriptive of the task carried out by the
function
statement
statement
Defining and Calling a Function
• Functions are given names
• Use tabs or spaces to indent lines in a block, but not both as this can
confuse the Python interpreter
output
expected
Anatomy of a Function
def function_name(param1, param2):
result = # do something
return result
return value
Designing a Program to Use Functions
• In a flowchart, function call shown as rectangle with vertical bars at
each side
• Typically draw separate flow chart for each function in the program
• End terminal symbol usually reads Return
• Box for each function in the program, Lines connecting boxes illustrate the
functions called by each function
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
def function_name(): scope!
x = 2
y = 3
Variable Scope
def main():
function_name()
print(y)
y is now out of
def function_name(): scope!
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,
def function_name(): we can use it in
x = 2
y = 3 main()
return y
Local Variables
• Local variable: variable that is assigned a value inside a function
• Only statements inside that function can access it, error will occur if
another function tries to access the variable
• Scope: the part of a program in which a variable may be accessed
• Each function does not see the other function’s local variables, so no
confusion
Passing Arguments to Functions
• Argument: piece of data that is sent into a function
• General format:
• def function_name(parameter):
def main():
a = 0
function_name()
print(a)
def function_name():
a = 3
print(a)
Think/Pair/Share:
def function_name():
a = 3
print(a)
Variable Scope
def main():
a = 0
a = function_name()
print(a)
def function_name():
a = 3
return a
Variable Scope
def print_my_variables():
x = 5
print(x)
print(y)
Variable Scope
def main():
y = 3
print_my_variables()
def print_my_variables():
x = 5
print(x)
print(y)
Variable Scope
def main():
y = 3
print_my_variables()
def print_my_variables():
x = 5
print(x)
print(y)
“do you have an x?”
Variable Scope
def main():
y = 3
print_my_variables()
def print_my_variables():
x = 5
print(x)
print(y)
“do you have an x?”
yes!
Variable Scope
def main():
y = 3
print_my_variables()
def print_my_variables():
x = 5
print(x)
print(y)
Variable Scope
def main():
y = 3
print_my_variables()
def print_my_variables():
x = 5
print(x)
print(y)
“do you have a y?”
Variable Scope
def main():
y = 3
print_my_variables()
def print_my_variables():
x = 5
print(x)
print(y)
“do you have a y?”
no...
Variable Scope
def main():
y = 3
print_my_variables()
def print_my_variables():
x = 5
print(x)
print(y)
“do you have a y?”
no... let’s ask the
caller!
Variable Scope
def main():
y = 3 “do you have a y?”
print_my_variables()
def print_my_variables():
x = 5
print(x)
print(y)
Variable Scope
def main():
y = 3 “do you have a y?”
print_my_variables()
yes!
def print_my_variables():
x = 5
print(x)
print(y)
Variable Scope what if...
def main():
print_my_variables()
def print_my_variables():
x = 5
print(x)
print(y)
Variable Scope
def main():
print_my_variables()
def print_my_variables():
x = 5
print(x) “do you have a y?”
print(y) no... let’s ask the
caller!
Variable Scope
def main():
print_my_variables() “do you have a y?”
def print_my_variables():
x = 5
print(x)
print(y)
Variable Scope
def main():
print_my_variables() “do you have a y?”
no...
def print_my_variables():
x = 5
print(x)
print(y)
Variable Scope
def main():
print_my_variables() “do you have a y?”
no... --> NameError
def print_my_variables():
x = 5
print(x)
print(y)
Scope [demo]
Variable Scope
def print_sale_price(supersale):
milk = 1.5
if supersale:
milk = 1
print(milk)
def main():
milk = 2
print_sale_price(True)
print(milk)
Keyword Arguments
• Keyword argument: argument that specifies which parameter the value
should be passed to
• Position when calling function is irrelevant
• General Format:
• function_name(parameter=value)
• Possible to mix keyword and positional arguments when calling a
function
• Positional arguments must appear first
Can I use data that does not change?
Global Variables and Global Constants
• Global variable: created by assignment statement written outside all the
functions
• Can be accessed by any statement in the program file, including from within a function
• If a function needs to assign a value to the global variable, the global variable must be redeclared
within the function
• Functions that use global variables are usually dependent on those variables
• To simulate global constant in Python, create global variable and do not re-declare it within
functions
Can I write my own value returning functions?
Writing Your Own Value-Returning Functions
• To write a value-returning function, you write a simple function and add
one or more return statements
• The value for expression will be returned to the part of the program that called the function
• The expression in the return statement can be a complex expression, such as a sum of two
variables or the result of another value- returning function
Writing Your Own Value-Returning Functions (cont’d.)
How to Use Value-Returning Functions
• Value-returning function can be useful in specific situations
• Example: have function prompt user for input and return the user’s input
• Common calculations, such as whether a number is even, can be easily repeated by calling a
function
expression2, etc.
• When you call such a function in an assignment statement, you need a separate variable on the
left side of the = operator to receive each returned value
Standard Library Functions and the import Statement
• Import the module containing the required function to each program that needs it
Storing Functions in Modules (cont’d.)
• Module is a file that contains Python code
• Contains function definition but does not contain calls to the functions
• The math module defines variables pi and e, which are assigned the
mathematical values for pi and e
• Can be used in equations that require these values, to get more accurate results
• Variables must also be called using the dot notation
• Example:
4 math.sqrt(4) 2.0
argument return
value
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
Menu Driven Programs
• Menu-driven program: displays a list of operations on the screen,
allowing user to select the desired operation
• List of operations displayed on the screen is called a menu
• Program uses a decision structure to determine the selected menu
option and required operation
• Typically repeats until the user quits
Think/Pair/Share:
[demo]
Generating Random Numbers
• Random number are useful in a lot of programming tasks
• random module: includes library functions for working with random
numbers
• Dot notation: notation for calling a function belonging to a module
• Format: module_name.function_name()
How do I create random data?
Generating Random Numbers (cont’d.)
• randint function: generates a random number in the range provided
by the arguments
• Returns the random number to part of program that called the function
● Interactive programs
How do we build programs that
Today’s interact with users?