Professional Documents
Culture Documents
4 Functions
4 Functions
Chapter 4
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))
return list
Programmer 1
ra m e ters
pa
Input
u t re turns
Outp
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