Function
TS. Trần Vũ Hoàng
Objectives
• In this chapter you will learn:
• To define and call a function
• Scopes of variables
• Arguments
• Some special functions
Why Use Function?
• Maximizing code reuse and minimizing redundancy
• Package logic you may wish to use in more than one place and more than
one time
• group and generalize code to be used arbitrarily many times later
• reduce code redundancy in our programs
• reduce maintenance effort
• Procedural decomposition
• functions would help you divide the overall task into chunks
• One function for each subtask in the process
Define a function
• Def statements:
• 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
• convert to immutable objects
Simulating Output Parameters
• Return can send back any sort of object
• Can return multiple values by packaging them in a tuple or other collection
type
• 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
• Keywords: match by name instead of by position
Special Argument-Matching Modes
• Defaults: if not passed a value, the argument is assigned its default before the
function runs
Special Argument-Matching Modes
• Combining keywords and defaults
Special Argument-Matching Modes
• Collecting arguments:
• *: collects unmatched positional arguments into a tuple
Special Argument-Matching Modes
• Collecting arguments:
• **: only works for keyword arguments, collects them into a new
dictionary
• can combine normal arguments, the *, and the ** to implement wildly
flexible call signatures
Special Argument-Matching Modes
• Unpacking arguments:
• we can use the * syntax when we call a function to unpack a collection of
arguments
• the ** syntax in a function call unpacks a dictionary of key/value pairs
into separate keyword arguments
Special Argument-Matching Modes
• Unpacking arguments:
• we can combine normal, positional, and keyword arguments in the call in
very flexible ways
Special Argument-Matching Modes
• arguments that appear after *args in the arguments list must be passed using
keyword syntax in the call
Special Argument-Matching Modes
• Keyword-only arguments: use a * character by itself in the arguments list to
indicate that a function does not accept a variable-length argument list but
still expects all arguments following the * to be passed as keywords
Special Argument-Matching Modes
• Can still use defaults for keyword-only arguments
• a may be passed by name or position
• b and c are optional but must be passed by keyword if used
Special Argument-Matching Modes
• Ordering rules
• keyword-only arguments must be specified after a single star
• not two—named arguments cannot appear after the **args arbitrary keywords form
• a ** can’t appear by itself in the arguments list
Special Argument-Matching Modes
• Ordering rules
• keyword-only arguments must be coded before the **args arbitrary keywords form
and after the *args arbitrary positional form
Example
• code a function that is able to compute the minimum value from an arbitrary
set of arguments and an arbitrary set of object data types
Example
• a single function to compute either a minimum or a maximum value
Recursive Functions
• recursive functions: functions that call themselves either directly or
indirectly in order to loop
• Example: summation with recursion
Recursive Functions
Indirect Function Calls
• the function name is simply a reference to an object—you can reassign that
object to other names freely and call it through any reference
Indirect Function Calls
• pass functions to other functions as arguments
Function attributes
• Function objects are not limited to the system-defined attributes listed
• it’s possible to attach arbitrary user-defined attributes to them
Anonymous Functions: lambda
• Besides the def statement, Python also provides an expression form that
generates function objects, it’s called lambda
• lambda returns the function instead of assigning it to a name
• Defaults work on lambda arguments, just like in a def:
Mapping Functions over Sequences: map
• updating all the counters in a list can be done easily with a for loop
• The map function applies a passed-in function to each item in an iterable
object and returns a list containing all the function call results
Mapping Functions over Sequences: map
• Can use lambda with map:
• map can be used in more advanced ways
Functional Programming Tools: filter and reduce
• filter: filter out items based on a test function
• reduce: apply functions to pairs of items and running results
Exercises
• Viết hàm tính tổng S=1+2+....+n
• Viết hàm kiểm tra số nguyên tố.
• Viết hàm tìm số lớn nhất trong 2 số.
• Viết chương trình Python có thể lọc các số chẵn trong danh sách sử dụng
hàm filter. Danh sách là [1,2,3,4,5,6,7,8,9,10].
• Gợi ý:
• Sử dụng filter() để lọc các yếu tố trong một list.
• Sử dụng lambda để định nghĩa hàm chưa biết.
Exercises
• Viết chương trình Python dùng map() để tạo list chứa các giá trị bình phương
của các số trong [1,2,3,4,5,6,7,8,9,10].
• Gợi ý:
• Sử dụng map() để tạo list.
• Sử dụng lambda để định nghĩa hàm chưa biết.
Exercises
• Viết chương trình Python dùng map() và filter() để tạo list chứa giá trị bình
phương của các số chẵn trong [1,2,3,4,5,6,7,8,9,10].
• Gợi ý:
• Dùng map() để tạo list.
• Dùng filter() để lọc thành phần trong list.
• Dùng lambda để định nghĩa hàm chưa biết.