04 Functions
04 Functions
Chapter 4
• Some related
3
modules can be put
into a file
• (You used it – math)
Structure Design: An example
Develop a program that will accept a positive integer then
sum of it’s divisors is printed out.
Analyze Code Description
Divide the program into n=0 Declare the main module
small tasks s=0 and it’s data
1- Accept n n = int(input(“Enter n =”)) Use a function input in the Python
2- s = sum of it’s divisors s = sumDivisors (n) Module will be implemented
3- Print out s print(f“sum = {s}”) Use a module print in the Python
4- Pause the program os.system("pause") Use a module system in os package
Characteristics of Modules
Characteristics Reason
It is easy to upgrade It contains a small group of code lines for a SPECIFIC
and maintain task.
•Each function has one entry point and one exit point
•Each function exhibits low coupling (sự phụ thuộc thấp). In the
best case, functions are independent.
Module identifying: Hints
n =0
• This defines the function but does not execute the body of the
function
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
Definitions and Uses
• Once we have defined a function, we can call (or invoke) it
as many times as we like
def print_lyrics():
print("I'm a lumberjack, and I'm okay.")
print('I sleep all night and I work all day.')
print('Yo')
print_lyrics()
Hello
x = x + 2
print(x) Yo
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
7
Function Definition
• In Python a function is some reusable code that takes
arguments(s) as input, does some computation, and then
returns a result or results
def greet():
return "Hello" Hello Glenn
Hello Sally
print(greet(), "Glenn")
print(greet(), "Sally")
Return Value
>>> def greet(lang):
... if lang == 'es':
• A “fruitful” function is one ... return 'Hola'
... elif lang == 'fr':
that produces a result (or ... return 'Bonjour'
return value) ... else:
... return 'Hello'
...
• The return statement ends >>> print(greet('en'),'Glenn')
the function execution and Hello Glenn
>>> print(greet('es'),'Sally')
“sends back” the result of Hola Sally
the function >>> print(greet('fr'),'Michael')
Bonjour Michael
>>>
Arguments, Parameters, and
Results
>>> big = max('Hello world') Parameter
>>> print(big)
w
def max(inp):
blah
blah
'Hello world' for x in inp: 'w'
blah
blah
Argument return 'w'
Result
Multiple Parameters / Arguments
• We can define more than one
parameter in the function def addtwo(a, b):
definition added = a + b
return added
• We simply add more arguments
x = addtwo(3, 5)
when we call the function print(x)
• We match the number and order 8
of arguments and parameters
Void (non-fruitful) Functions
Analysis Analysis
Enter Hours: 45
Enter Rate: 10
Pay: 475.0
475 = 40 * 10 + 5 * 15