5 PythonLfunctions PDF
5 PythonLfunctions PDF
2
Some useful functions from the module
random
⚫ randint(a, b): “return” a random (arbitrary) integer N such that
a ≤ N ≤ b.
⚫ random(): return a random float number R such that
0.0 ≤ R < 1.0
⚫ choice(mylist): return a random item in the list mylist.
3
Some useful functions from the module
random
4
Some obvious facts about
functions:
⚫ A function must have a unique name. We call a function by its
name.
⚫ A function may or may not “return” a value.
⚫ sqrt(m): returns the square of m
⚫ A function may need some arguments, and the value it returns
depends on these arguments.
⚫ random(): no argument
⚫ sqrt(m) has one float argument.
⚫ randint(a, b): has two int arguments.
5
Composition of functions
⚫ The return value of a function can be used directly as an
argument of another function.
6
Define our own functions
Syntax:
def function_name(arg_list):
statement_body
must be indented.
7
Executing a function
8
Executing a function
execution jumps
to the beginning
of the called
function,
and its statements
are executed one
by one.
9
Executing a function
when all the statements
of the function are
executed, control returns
back to the suspended
point in main, and the
following statement is
executed.
10
A function can call other functions
11
function with arguments
12
function with arguments
x=a
y=b
13
Another way to exit a function call: return
with a value
14
Another way to exit a function call: return
with a value
x = m (== 4)
Suppose m = 4
True
15
A more complicated function
16
A more complicated function
17
A more complicated function
Many programmers
prefer defining a
function call “main()”,
which contains the
main part of the programs.
18
A more complicated function
19
Local vs Global variables
⚫ local variables: variables in a function definition are local to
that function, and cannot be accessed outside the function.
20
⚫ Variables appear outside any function definitions are global
and can be accessed by all the following statements/functions;
but not before them as they are not defined yet.
21
map: applies a function to all the items in
an input_list
⚫ Syntax:
map(function_to_apply, list_of_inputs)
22
filter: creates a list of elements for which a
function returns true.
Syntax:
filter(function_to_apply, list_of_inputs)
23
Define one line function using lambda
⚫ Syntax:
lambda argument: expression on the argument
⚫ Example
24
Use lambda with map, filter
25
checking within a one-line function
26
checking within a one-line function
27
A question in last semester’s
midterm
Write a complete Python program that reads an integer, then
multiply it by 2, and print the sum of the digits in the result. For
example, if the input is 123, then your program should output
12 because 123 x 2 = 246 and 2+4+6 = 12.
28
Another question
⚫ Given two lists of integers, print the integers that are in both
lists.
29