

Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
An introduction to functions in python, explaining their definition, call, parameters, and return statements. It covers the anatomy of a function definition, including the function header, docstring, and function body. The document also includes examples and exercises to help readers understand the concepts.
Typology: Schemes and Mind Maps
1 / 2
This page cannot be seen from the preview
Don't miss anything!


>>> plus( 23 )
def plus(n):
return n+
the parentheses of a method header.
parameter when it is called
Function
Header Function
Body
(indented)
Function Header
name parameters
Docstring
Specification
Statements to
execute when called
The vertical line
indicates indentation
Use vertical lines when you write Python
on exams so we can see indentation
x?
D: Nothing!
E: I do not know
function body to execute next
Draw parameters
as variables
(named boxes)
function name
local variables (later in lecture)
parameters
instruction counter
def to_centigrade(x):
return 5*(x-32)/9.
to_centigrade 1
x 50.
to_centigrade
x ā > 50.
to the parameter (in frame)
§ Look for variables in the frame
§ If not there, look for global
variables with that name
def to_centigrade(x):
return 5*(x-32)/9.
to_centigrade 1
x
Initial call frame
(before exec body)
next line to execute
to the parameter (in frame)
§ Look for variables in the frame
§ If not there, look for global
variables with that name
def to_centigrade(x):
return 5*(x-32)/9.
to_centigrade
x
Executing the
return statement
Return statement creates a
1 special variable for result
RETURN
a 1 b 2
swap
a 1 b 2
tmp 1
Global Space
(for globals.py)
§ math.cos: global for math
§ temperature.to_centigrade
uses global for temperature
§ Assignment to a global
makes a new local variable!
§ Why we limit to constants
get_a 1
a 4
"""Show how globals work"""
a = 4 # global space
def get_a():
return a # returns global
Global Space
(for globals.py)
§ math.cos: global for math
§ temperature.to_centigrade
uses global for temperature
§ Assignment to a global
makes a new local variable!
§ Why we limit to constants
change_a
a 3.
a 4
"""Show how globals work"""
a = 4 # global space
def change_a():
a = 3.5 # local variable
return a
>>> x = foo(3,4)