0% found this document useful (0 votes)
6 views31 pages

04 Functions

The document discusses Python functions, including built-in and user-defined functions, and the importance of structuring code into modules for better organization and reusability. It explains the concepts of parameters, arguments, return values, and the distinction between fruitful and void functions. Additionally, it emphasizes the need for clear function definitions and the benefits of using functions to avoid code repetition and manage complexity.

Uploaded by

Trong Nguyen Duc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views31 pages

04 Functions

The document discusses Python functions, including built-in and user-defined functions, and the importance of structuring code into modules for better organization and reusability. It explains the concepts of parameters, arguments, return values, and the distinction between fruitful and void functions. Additionally, it emphasizes the need for clear function definitions and the benefits of using functions to avoid code repetition and manage complexity.

Uploaded by

Trong Nguyen Duc
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 31

Functions

Chapter 4

Python for Everybody


www.py4e.com
Python Functions
• There are two kinds of functions in Python.

- Built-in functions that are provided as part of Python - print(),


input(), type(), float(), int() ...

- Functions that we define ourselves and then use

• We treat function names as “new” reserved words


(i.e., we avoid them as variable names)
Modules: Structure Design
In designing a program, we subdivide the problem
conceptually into a set of design units. We call these design
units as modules. In subdividing the problem, we reduce the
Modules: Structure Design
number of factors with which to deal simultaneously.

• 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.

It can be re-used in the It has a identified name ( a descriptive identifier) and


same program can be used more than one time in a program.

It can be re-used in if it is stored in an outside file (library file), it can be


some programs used in some programs.
Function identifying: Hints
In a structured design

•Each function has one entry point and one exit point

•Each function is highly cohesive (performs a single task – tính


gắn kết cao ), code of a module focuses to the determined
purpose and some related modules are put in one file.

•Each function exhibits low coupling (sự phụ thuộc thấp). In the
best case, functions are independent.
Module identifying: Hints
n =0

Module for summing divisors of n


accept n
sum of it’s divisors
Lowly cohesive
An input High coupling
operation in a Module for printing out divisors of n Some modules
processing accept n access a
Print out it’s divisors common data is
module is not
encouraged. not encouraged.
 All the code in  All modules
a module focus #main program should be self-
to the purpose of access n contained
the module (independent)
Building our Own Functions
• We create a new function using the def keyword followed by
optional parameters in parentheses

• We indent the body of the function

• 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

• This is the store and reuse pattern


x = 5
print('Hello')

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

• We define a function using the def reserved word

• We call/invoke the function by using the function name,


parentheses, and arguments in an expression
Function Definition
Function Definition
Parameters
>>> def greet(lang):
... if lang == 'es':
A parameter is a variable which ... print('Hola')
... elif lang == 'fr':
we use in the function definition. ... print('Bonjour')
... else:
It is a “handle” that allows the ... print('Hello')
code in the function to access ...
>>> greet('en')
the arguments for a particular Hello
function invocation. >>> greet('es')
Hola
>>> greet('fr')
Bonjour
>>>
Arguments
• An argument is a value we pass into the function as its input
when we call the function

• We use arguments so we can direct the function to do different


kinds of work when we call it at different times

• We put the arguments in parentheses after the name of the


function
big = max('Hello world')
Argument
Stored (and reused) Steps
def
show(s): Program:
Parameter
print('Hello’+s) def show(s):
print('Hello’+s)

show(“Tom”) #end show


Argument
print('Zip') show(“Tom”) Output:
print('Zip’)
show(“David”)
show(“David”) Hello Tom
Zip
We call these reusable pieces of code “functions” Hello David
Return Values
Often a function will take its arguments, do some computation, and
return a value to be used as the value of the function call in the
calling expression. The return keyword is used for this.

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

• When a function does not return a value, we call it a “void”


function

• Functions that return values are “fruitful” functions


• Void functions are “not fruitful”
To function or not to function...
• Organize your code into “paragraphs” - capture a complete
thought and “name it”

• Don’t repeat yourself - make it work once and then reuse it

• If something gets too long or complex, break it up into logical


chunks and put those chunks in functions

• Make a library of common stuff that you do over and over -


perhaps share this with your friends...
Demo-01
Demo-02
Demo-03
Develop a program that will accept a positive integer then sum of it’s divisors
is printed out
Demo-04
Develop a program that will print out the n first primes.

Analysis Analysis

- Nouns: the integer n  int n Function print_n_Primes ( n )


- Verbs: int count = 0;
- Begin int value = 2;
- Accept n  simple while count <n :
- Print n first primes  if value is a prime  function
function count = count +1;
- End. print out value;  simple
#end if
value = value +1;
Input: n=5 #end while
Output: 2, 3, 5, 7, 11 #end function
Demo-04
Type Conversions
>>> print(float(99) / 100)
• When you put an integer 0.99
>>> i = 42
and floating point in an >>> type(i)
expression, the integer <class 'int'>
is implicitly converted to >>> f = float(i)
>>> print(f)
a float
42.0
>>> type(f)
• You can control this with <class 'float'>
the built-in functions int() >>> print(1 + 2 * float(3) / 4 – 5)
and float() -2.5
>>>
String >>> sval = '123'
>>> type(sval)

Conversions <class 'str'>


>>> print(sval + 1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot concatenate 'str'
• You can also use int() and and 'int'
float() to convert between >>> ival = int(sval)
>>> type(ival)
strings and integers <class 'int'>
>>> print(ival + 1)
• You will get an error if the 124
>>> nsv = 'hello bob'
string does not contain >>> niv = int(nsv)
numeric characters Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int()
Summary
• Functions • Arguments
• Built-In Functions • Results (fruitful functions)
• Type conversion (int, float) • Void (non-fruitful) functions
• String conversions • Why use functions?
• Parameters
Exercise

Rewrite your pay computation with time-and-a-


half for overtime and create a function called
computepay which takes two parameters ( hours
and rate).

Enter Hours: 45
Enter Rate: 10

Pay: 475.0
475 = 40 * 10 + 5 * 15

You might also like