0% found this document useful (0 votes)
11 views33 pages

4 Functions

Uploaded by

jdskk
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)
11 views33 pages

4 Functions

Uploaded by

jdskk
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/ 33

Functions

Chapter 4

An Introduction to Programming Using Python


David I. Schneider
Built-in Functions
• Table 4.1 Some Python built-in functions.
• https://docs.python.org/3/library/functions.html
User-defined Functions
• Defined by statements of the form

– par1, par2 are variables (called parameters)


– Expression evaluates to a literal of any type
– Header must end with colon
– Each statement in block indented same
– Parameters and return statements optional in function definitions
– Function names should describe the role performed
Passing a Value to a Function
• Example 3: Program shows there is no change
in the value of the argument
파일명

multiply.py 함수명

def triple(num):
num = 3 * num
return num
def multiple(num):
num = 2 * num
return num
파일 ( 명 )
shell 가져오기
>>> import multiply
>>> a=5
>>> multiply.triple(a)
>>> multiply.multiple(a)

파일명 함수명
Passing a Value to a Function
• Question: power to the 3 (EX: num3)

파일명

multiply.py 함수명

def triple(num):
num = 3 * num
return num
파일 가져오기
shell
>>> import triple
>>> a=5
>>> multiply.triple(5)

파일명 함수명
Functions Having One Parameter
• Example 1: Program uses the function
fahrenheitToCelsius
• parameters F, return C
• C = (5/9) * (F – 32)
Functions Having One Parameter
• Example 1: Program uses the function
fahrenheitToCelsius
• C = (5/9) * (F – 32)
Functions Having One Parameter
• Example 2: Program uses the function
firstName
Functions Having Several Parameters
Passing by position
• Example: adder a = 5, b = 7, c=2
def adder(x,y,z):
sum = x + y + z
Input
parameters
def adder(x,y,z):
return sum
a=5 Input
b=7 arguments adder(a,b,c)
c=2
print(adder(a,b,c))

• Question: average of a = 5, b = 7, c=2


Functions Having Several Parameters
Passing by Parameter Name
• Example: adder a = 5, b = 7, c=2
def adder(x,y,z): def adder(x,y,z):
sum = x + y + z sum = x + y + z
return sum return sum
a=5 print(adder(x=5,y=7,z=2)) #ex1
b=7 print(adder(z=2,x=5,y=7)) #ex2
c=2
print(adder(a,b,c))

• Question: average of a = 5, b = 7, c=2


Functions Returning
Multiple Values
• Functions can return any type of object
– Function can return a tuple.
• Example 2: balanceAndInterest function
returns a tuple
– Giving values associated with deposit into savings
account.
Functions Returning
Multiple Values
• Example: adder & multiplier a = 5, b = 7, c=2
def addAndMulti(x,y,z): output
sum = x + y + z arguments return (sum, multiply)
multiply = x*y*z
return (sum, multiply)
a=1 output
b=2 parameters
c=3
(add, mul) = addAndMulti(a,b,c) (add, mul) = addAndMulti(a,b,c)
print(add, mul)

• Question: sum & average a = 1, b = 2, c=3


Default Values
• Parameters of a function can have default values
– Assigned to them when no values are passed to them
• Format for definition using default values

• Table 4.4 Three function calls


Default Values

• Example: adder a = 5, b = 7, c=2 Parameters


with default

def adder(x,y,z): def adder(x=0,y=0,z=0):


sum = x + y + z sum = x + y + z
return sum return sum
a=5 a=5 Less number
of inputs
b=7 b=7
c=2 c=2
print(adder(a,b,c)) print(adder(a))
print(adder(a,b))
print(adder(a,b,c))

• Question: multiply of a = 5, b = 7, c=2


Functions that do not Return Values
• Example 8: Program displays three verses of
children’s song.
Functions without Parameters
• Example 9: Program calculates the population density of a
state
Return boolean
• Example 6: Program uses a Boolean-valued
function to
determine
whether return Boolean
(True or False)
input is a
vowel word
Function with
Boolean return
(True or False)
Return list
• Example 7: Program uses a list-valued function

return list

© 2016 Pearson Education, Inc.,Hoboken, NJ.  All rights reserved.


Functions from the
random Module
• Functions that randomly select items from a
list and randomly reorder the items in a list.
• Example 1: Program demonstrates functions
from the random module.
Functions Calling Other Functions
• Example: sum & average of a = 5, b = 7, c=2
adder
average.py Adder average.py function
statement
def average(x,y,z): def average(x,y,z):
sum = x+y+z sum = adder(x,y,z)
avg = (x+y+z) / 3 avg = adder(x,y,z) / 3
return (sum, avg) return (sum, avg)
a=5 def adder(d,e,f):
b=7 sum = d + e + f
c=2 return sum
print(average(a,b,c))
a=5
b=7
c=2
print(average(a,b,c))
Library Modules
• A library module is a file with extension .py
– Contains functions and variables
– Can be used (imported) by any program
– can be created in IDLE or any text editor
– Looks like an ordinary Python program
• To gain access to the functions and variables
– place a statement of the form import moduleName
at the beginning of the program
Library Modules

• Example: sum & average of a = 5, b = 7, c=2


import
average.py average.py adder file
def average(x,y,z): import add Call adder function
sum = adder(x,y,z) in add file
avg = adder(x,y,z) / 3 def average(x,y,z):
return (sum, avg) sum = add.adder(x,y,z)
avg = add.adder(x,y,z) / 3
def adder(d,e,f): return (sum, avg)
sum = d + e + f
return sum a=5
b=7
a=5 c=2
b=7 print(average(a,b,c))
c=2
print(average(a,b,c)) add.py
def adder(d,e,f):
sum = d + e + f
return sum
Top-Down Design

Programmer 1

ra m e ters
pa
Input
u t re turns
Outp

programmer 2 programmer 3 programmer 4

Figure 4.33 Beginning of a hierarchy chart for


the car loan program.
Top-Down Design

Figure 4.34 Hierarchy chart for the car loan program.


Scope of Variables
• Variable created inside a function can only be
accessed by statements inside that function
– Ceases to exist when the function is exited
• Variable is said to be local to function or to
have local scope
• If variables created in two different functions
have the same name
– They have no relationship to each other
Scope of Variables
• Example 10: Variable x in the function main,
variable x in the function trivial are different
variables
Scope of Variables
• Scope of a variable is the portion of the
program that can refer to it
• To make a variable global, place assignment
statement that creates it at top of program.
– Any function can read the value of a global a=3

variable def test1():


a=0

def test2():
global a
a=4
• Convention programmers use print(a)
– Name written in uppercase letters test1()
print(a)

test2()
print(a)
Library Modules
main.py file2.py main.py
def test1(): a=3
a=3 a=0 Import file2
Import file3
def test1():
a=0 print(a)
def test2(): file3.py file2.test1()
global a print(a)
a=4 def test2():
global a
a=4 file3.test2()
print(a) print(a)
test1()
print(a)
file2.py main.py
test2()
print(a) def test1(): a=3
a=0 Import file2
def test2():
global a print(a)
a=4
file2.test1()
print(a)

file2.test2()
print(a)
Scope of Variables
• trivial() 수행 후 x 값이 변경되도록 수정하라 .
EX:
def main(): a=3
x=2
print(str(x) + ": function main") def test1():
trivial() a=0
print(str(x) + ": function main")
def test2():
def trivial(): global a
x=3 a=4
print(str(x) + ": function main")
print(a)
main()
test1()
print(a)

test2()
print(a)
Homework
• chapter 4.1: 25, 28, 29
• chapter 4.2: 49, 50, 52, 69

You might also like