Chap 4
Chap 4
• Return statements: end the function call and send a result back to the caller
Call a function
• It’s completely legal to nest a function def inside an if statement
• can be assigned to a different name and called through the new name
Examples
def intersect(seq1, seq2):
res = [] # Start empty
for x in seq1: # Scan seq1
if x in seq2: # Common item?
res.append(x) # Add to end
return res
Calls:
Scopes
• Function’s namespace:
• Names defined inside a def can only
be seen by the code within that def
• You cannot even refer to such names
from outside the function
• A name X assigned outside a given def
is a completely different variable from a
name X assigned inside that def.
• Local: variables inside a def
• Nonlocal: variables in an enclosing def
• Global: variables outside all defs
Global statement
• The global statement tells Python that a function plans to change one or more
global names
Other ways to access globals
Other ways to access globals
Nonlocal statements
• nonlocal statement: only inside a function
def func():
nonlocal name1, name2, ...
• allows a nested function to change one or more names defined in a syntactically enclosing
function’s scope
def tester(start):
state = start # Each call gets its own state
def nested(label):
nonlocal state # Remembers state in enclosing scope
print(label, state)
state +=1 # Allowed to change it if nonlocal
return nested
F = tester(0)
F('spam’) # Increments state on each call
Arguments
• Arguments are passed by automatically assigning objects to local variable
names
• Assigning to argument names inside a function does not affect the caller
• Changing a mutable object argument in a function may impact the caller
Arguments
• Arguments are passed by automatically assigning objects to local variable
names
• Assigning to argument names inside a function does not affect the caller
• Changing a mutable object argument in a function may impact the caller
Avoiding Mutable Argument Changes
• make explicit copies of mutable objects
• It looks like the code is returning two values here, but it’s really just one—a
two-item tuple with the optional surrounding parentheses omitted
Special Argument-Matching Modes
• Python matches names by position from left to right, like most other
languages