생능출판사 (가칭)"데이터과학 파이썬" 코드 6장

6.2 def 예약어를 이용하여 함수를 작성하고 호출하기

In [1]:
def print_address() :
    print('°æ»óºÏµµ')
    print('¿ï¸ª±º ¿ï¸ªÀ¾')
    print('µ¶µµ¸® »ê 1-96¹øÁö')

print_address()  # Á¤ÀÇÇÑ ÇÔ¼ö¸¦ È£Ãâ
°æ»óºÏµµ
¿ï¸ª±º ¿ï¸ªÀ¾
µ¶µµ¸® »ê 1-96¹øÁö

6.3 왜 우리는 함수를 작성하는가?

In [2]:
print('°æ»óºÏµµ')
print('¿ï¸ª±º ¿ï¸ªÀ¾')
print('µ¶µµ¸® »ê 1-96¹øÁö')
°æ»óºÏµµ
¿ï¸ª±º ¿ï¸ªÀ¾
µ¶µµ¸® »ê 1-96¹øÁö
In [3]:
print_address()
print_address()
print_address()
°æ»óºÏµµ
¿ï¸ª±º ¿ï¸ªÀ¾
µ¶µµ¸® »ê 1-96¹øÁö
°æ»óºÏµµ
¿ï¸ª±º ¿ï¸ªÀ¾
µ¶µµ¸® »ê 1-96¹øÁö
°æ»óºÏµµ
¿ï¸ª±º ¿ï¸ªÀ¾
µ¶µµ¸® »ê 1-96¹øÁö

6.4 함수에 1개의 입력 전달하기

In [4]:
def print_address(name):
    print("¼­¿ï Ưº°½Ã Á¾·Î±¸ 1¹øÁö")
    print("ÆÄÀ̽㠺ôµù 7Ãþ")
    print(name)

print_address("È«±æµ¿")
¼­¿ï Ưº°½Ã Á¾·Î±¸ 1¹øÁö
ÆÄÀ̽㠺ôµù 7Ãþ
È«±æµ¿

6.5 값 반환하기

In [5]:
def calculate_area(radius): 
    area = 3.14 * radius**2 
    return area      # ÀÌÀü ÁÙ¿¡¼­ ±¸ÇÑ area °ªÀ» È£Ãâ¹®¿¡ µ¹·ÁÁØ´Ù
In [6]:
c_area = calculate_area(5.0)   # calculate_are() ÇÔ¼ö°¡ °è»êÇÑ °ªÀ» c_area¿¡ ÀúÀå
In [7]:
print(calculate_area (5.0))
78.5
In [8]:
area_sum = calculate_area(5.0) + calculate_area(10.0)
print(area_sum)
392.5
In [9]:
calculate_area(10.0)   # ÇÔ¼ö¸¦ È£Ã⸸ ÇÏ°í ±× ¹Ýȯ°ªÀ» »ç¿ë¾ÈÇÔ
Out[9]:
314.0

6.6 여러 개의 값 반환하기

In [10]:
def sort_num(n1, n2):      # 2°³ÀÇ °ªÀ» ¹Þ¾Æ¿À´Â ÇÔ¼ö
    if n1 < n2:
        return n1, n2      # n1ÀÌ ´õ ÀÛÀ¸¸é n1, n2 ¼ø¼­·Î ¹Ýȯ
    else:
        return n2, n1      # n2°¡ ´õ ÀÛÀ¸¸é n2, n1 ¼ø¼­·Î ¹Ýȯ

print(sort_num(110, 210))  # 110°ú 210À» ÇÔ¼öÀÇ ÀÎÀÚ·Î Àü´ÞÇÏ°í ¹ÝȯµÇ´Â °ªÀ» Ãâ·Â
print(sort_num(2100, 80))
(110, 210)
(80, 2100)
In [11]:
def calc(n1, n2):
    return n1 + n2, n1 - n2, n1 * n2, n1 / n2  # µ¡¼À, »¬¼À, °ö¼À, ³ª´°¼À °á°ú¸¦ ¹Ýȯ

n1, n2 = 200, 100
t1, t2, t3, t4 = calc(n1, n2)  # ³× °³ÀÇ °ªÀ» ¹Ýȯ¹Þ±â À§ÇØ 4°³ÀÇ º¯¼ö¸¦ »ç¿ëÇÔ
print(n1, '+', n2, '=', t1)
print(n1, '-', n2, '=', t2)
print(n1, '*', n2, '=', t3)
print(n1, '/', n2, '=', t4)
200 + 100 = 300
200 - 100 = 100
200 * 100 = 20000
200 / 100 = 2.0

6.7 함수에 여러 개의 값을 전달하기

In [12]:
def get_sum(start, end):   # start, end¸¦ ¸Å°³º¯¼ö·ÎÇÏ¿© ÀÎÀÚ¸¦ ¹Þ´Â´Ù
    s = 0 
    for i in range(start, end+1): # startºÎÅÍ end±îÁö Á¤¼öÀÇ ÇÕÀ» ±¸ÇÔ
        s += i 
    return s    # startºÎÅÍ end±îÁö ¼öÀÇ ÇÕÀ» ¹ÝȯÇÑ´Ù
 
print(get_sum(1, 10)) # 1¿¡¼­ 10±îÁö Á¤¼öÀÇ ÇÕ 55¸¦ Ãâ·ÂÇÑ´Ù
55
In [13]:
x = get_sum(1, 10)    # 1°ú 10ÀÌ get_sum()ÀÇ ÀÎÀÚ°¡ µÈ´Ù. 
print('x =', x)

y = get_sum(1, 20)    # 1°ú 20ÀÌ get_sum()ÀÇ ÀÎÀÚ°¡ µÈ´Ù. 
print('y =', y)
x = 55
y = 210

LAB 6-1 사각형을 그리는 함수 작성하기

In [14]:
import turtle 

t = turtle.Turtle() 
t.shape("turtle") 

def square(length):       # length´Â ÇѺ¯ÀÇ ±æÀÌ 
    for i in range(4): 
        t.forward(length) 
        t.left(90) 
 
square(100)      # square() ÇÔ¼ö¸¦ È£ÃâÇÑ´Ù. 
square(200)      # È£Ãâ½Ã ÀÎÀÚ°ªÀ» 100, 200, 300À¸·Î ´Ù¸£°Ô ÇÑ´Ù
square(300) 

turtle.done()
try:
    turtle.bye()
except:
    print("bye") 
bye

LAB 6-2 n-각형을 그리는 함수 작성하기

In [15]:
import turtle 
t = turtle.Turtle() 
 
# n-°¢ÇüÀ» ±×¸®´Â ÇÔ¼ö¸¦ Á¤ÀÇÇÑ´Ù. 
def n_polygon(n, length): 
    for i in range(n): 
        t.forward(length) 
        t.left(360//n)      # Á¤¼ö ³ª´°¼ÀÀº //À¸·Î ÇÑ´Ù. 
 
for i in range(10): 
    t.left(20) 
    n_polygon(6, 100) 
    
turtle.done()
try:
    turtle.bye()
except:
    print("bye")     
bye

6.8 변수의 범위

In [16]:
def print_counter():
    print('counter =', counter)  # ÇÔ¼ö ³»ºÎÀÇ counter °ª

counter = 100
print_counter()
print('counter =', counter)      # ÇÔ¼ö ¿ÜºÎÀÇ counter °ª
counter = 100
counter = 100
In [17]:
def print_counter():
    counter = 200
    print('counter =', counter)  # ÇÔ¼ö ³»ºÎÀÇ counter °ª

counter = 100
print_counter()
print('counter =', counter)      # ÇÔ¼ö ¿ÜºÎÀÇ counter °ª
counter = 200
counter = 100

6.9 함수 안에서 전역변수 사용하기

In [18]:
def print_counter():
    global counter      # ÇÔ¼ö ¿ÜºÎÀÇ Àü¿ªº¯¼ö counter¸¦ »ç¿ëÇÏ°Ú´Ù´Â ¼±¾ð
    counter = 200
    print('counter =', counter)  # ÇÔ¼ö ³»ºÎÀÇ counter °ª

counter = 100
print_counter()
print('counter =', counter)      # ÇÔ¼ö ¿ÜºÎÀÇ counter °ª
counter = 200
counter = 200
In [19]:
def calculate_area(radius): 
    global area 
    area = 3.14 * radius**2 
    return 
 
area = 0 
r = float(input("¿øÀÇ ¹ÝÁö¸§: ")) 
calculate_area(r) 
print(area) 
¿øÀÇ ¹ÝÁö¸§: 10
314.0

6.10 디폴트 인자

In [20]:
def greet(name, msg): 
    print("¾È³ç", name + ', ' + msg) 
 
greet("ö¼ö", "ÁÁÀº ¾Æħ!")
¾È³ç ö¼ö, ÁÁÀº ¾Æħ!
In [21]:
greet("¿µÈñ")    # ÀÎÀÚ¸¦ 1°³¸¸ Àü´ÞÇÏ¿© greet()À» È£ÃâÇÔ
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-21-4261a76d49a5> in <module>
----> 1 greet("¿µÈñ")    # ÀÎÀÚ¸¦ 1°³¸¸ Àü´ÞÇÏ¿© greet()À» È£ÃâÇÔ

TypeError: greet() missing 1 required positional argument: 'msg'
In [22]:
def greet(name, msg="º°ÀϾøÁÒ?"): 
    print("¾È³ç", name + ', ' + msg) 
 
greet("¿µÈñ")
greet("ö¼ö")
greet("¹Î¼ö", "Àß Áö³»°í ÀÖÀ¸½ÃÁÒ?")
¾È³ç ¿µÈñ, º°ÀϾøÁÒ?
¾È³ç ö¼ö, º°ÀϾøÁÒ?
¾È³ç ¹Î¼ö, Àß Áö³»°í ÀÖÀ¸½ÃÁÒ?

6.11 키워드 인자

In [23]:
def power(base, exponent): 
    return base**exponent   # base°¡ ¹ØÀÌ°í, exponent°¡ Áö¼ö°ªÀÌ´Ù.
In [24]:
 power(2, 10)  # 2ÀÇ 10½ÂÀ» ¹ÝȯÇÑ´Ù
Out[24]:
1024
In [25]:
power(10, 2)  # 10ÀÇ 2½ÂÀ» ¹ÝȯÇÑ´Ù
Out[25]:
100
In [26]:
power(base=2, exponent=10)  # 2ÀÇ 10½ÂÀ» ¹ÝȯÇÑ´Ù
Out[26]:
1024
In [27]:
power(exponent=10, base=2)  # 2ÀÇ 10½ÂÀ» ¹ÝȯÇÑ´Ù
Out[27]:
1024
In [28]:
power(base = 10, 2)
  File "<ipython-input-28-1d2882bbce62>", line 1
    power(base = 10, 2)
                    ^
SyntaxError: positional argument follows keyword argument

LAB 6-3 주급 계산 프로그램

In [29]:
def weeklyPay(rate, hour): 
    if (hour > 30): 
        money = rate*30 + 1.5*rate*(hour-30)
    else: 
        money = rate*hour
    return money

r = int(input("½Ã±ÞÀ» ÀÔ·ÂÇϽÿÀ: "))       # ½Ã±ÞÀԷ¹ޱâ
h = int(input("±Ù¹« ½Ã°£À»  ÀÔ·ÂÇϽÿÀ: ")) # ±Ù¹«½Ã°£ ÀԷ¹ޱâ
print("ÁÖ±ÞÀº " + str(weeklyPay(rate = r, hour = h)))
½Ã±ÞÀ» ÀÔ·ÂÇϽÿÀ: 10000
±Ù¹« ½Ã°£À»  ÀÔ·ÂÇϽÿÀ: 38
ÁÖ±ÞÀº 420000.0

LAB 6-4 리스트에서 최대값을 찾는 함수

In [30]:
def getMinMax(mylist, method = 'max'):
   minValue = 999999999999999999999999999999999
   maxValue = -minValue

   if method == 'max' :
       for value in mylist:
           if value > maxValue:
               maxValue = value;
       return maxValue
   elif method == 'min' :
       for value in mylist:
           if value < minValue:
               minValue = value;
       return minValue
   else :
       print('illegal method')

list_data = [27, 90, 30, 87, 56]
i=0
while(True) :
   print(list_data)
   method_input = input('ÃÖ´ë°ªÀ» ¿øÇϸé max, ÃÖ¼Ò°ªÀ» ¿øÇϸé minÀ» ÀÔ·ÂÇϽÿÀ: ')
   print(getMinMax(list_data, method_input))
   i+=1
   if(i==4):
    break
[27, 90, 30, 87, 56]
ÃÖ´ë°ªÀ» ¿øÇϸé max, ÃÖ¼Ò°ªÀ» ¿øÇϸé minÀ» ÀÔ·ÂÇϽÿÀ: min
27
[27, 90, 30, 87, 56]
ÃÖ´ë°ªÀ» ¿øÇϸé max, ÃÖ¼Ò°ªÀ» ¿øÇϸé minÀ» ÀÔ·ÂÇϽÿÀ: max
90
[27, 90, 30, 87, 56]
ÃÖ´ë°ªÀ» ¿øÇϸé max, ÃÖ¼Ò°ªÀ» ¿øÇϸé minÀ» ÀÔ·ÂÇϽÿÀ: minmax
illegal method
None
[27, 90, 30, 87, 56]
ÃÖ´ë°ªÀ» ¿øÇϸé max, ÃÖ¼Ò°ªÀ» ¿øÇϸé minÀ» ÀÔ·ÂÇϽÿÀ: max
90

LAB 6-5 막대 그래프 그리기

In [31]:
import turtle 

def drawBar(height): 
    t.begin_fill()
    t.left(90)
    t.forward(height)
    t.write(str(height), font = ('Times New Roman', 16, 'bold'))
    t.right(90)
    t.forward(40)
    t.right(90)
    t.forward(height)
    t.left(90)
    t.end_fill()

data = [120, 56, 309, 220, 156, 23, 98] 
 
t = turtle.Turtle() 
t.color("blue") 
t.fillcolor("red")  
t.pensize(3) 
 
for d in data: 
    drawBar(d) 
    
turtle.done()
try:
    turtle.bye()
except:
    print("bye")     
bye

LAB 6-6 함수 그리기

In [35]:
import turtle 
t = turtle.Turtle() 
t.shape("turtle") 
t.speed(0) 
 
def f(x): 
    return x**2 + 1 
 
t.goto(200, 0) 
t.goto(0, 0) 
t.goto(0, 200) 
t.goto(0, 0) 
 
for x in range(150): 
    t.goto(x, int(0.01*f(x)))

turtle.done()
try:
    turtle.bye()
except:
    print("bye")            
bye

6.12 자기자신을 호출하는 재귀 함수

In [36]:
def factorial(n):                   # n!ÀÇ Àç±ÍÀû ±¸Çö
    if n <= 1 :                     # Á¾·á Á¶°ÇÀÌ ¹Ýµå½Ã ÇÊ¿äÇÏ´Ù			
        return 1 
    else :				
        return n * factorial(n-1)   # n * (n-1)! Á¤ÀÇ¿¡ µû¸¥ ±¸Çö 

print('4! = ', factorial(4))        # ÀÎÀÚ·Î 4¸¦ ³Ö¾î È£Ãâ
4! =  24

LAB 6-7 피보나치 함수 계산하기

In [37]:
def fibonacci(n): 
    if n<0:                                   # ÀÔ·Â ¿À·ù °Ë»ç
        print("À߸øµÈ ÀÔ·ÂÀÔ´Ï´Ù.") 
    elif n==1:                                # Àç±ÍÈ£Ãâ Áß´Ü Á¶°Ç
        return 0 
    elif n==2:                                # Àç±ÍÈ£Ãâ Áß´Ü Á¶°Ç
        return 1 
    else: 
        return fibonacci(n-1) + fibonacci(n-2)  # Àç±ÍÈ£Ãâ

i = int(input("¸î ¹ø° Ç×: ")) 
print(fibonacci(i))  
¸î ¹ø° Ç×: 7
8

6.13 모듈을 이용한 함수의 재활용

In [38]:
import datetime              # ³¯Â¥¿Í ½Ã°£À» ´Ù·ç´Â ¸ðµâ
datetime.datetime.now()
Out[38]:
datetime.datetime(2022, 3, 24, 2, 37, 2, 619067)
In [39]:
today = datetime.date.today()
print(today)
2022-03-24
In [40]:
today
Out[40]:
datetime.date(2022, 3, 24)
In [41]:
today.year
Out[41]:
2022
In [42]:
today.month
Out[42]:
3
In [43]:
today.day
Out[43]:
24

6.14 나만의 모듈을 만들고 불러서 사용해 보자

In [44]:
# filename: my_func.py
def mf_print(msg, n = 1) :
   print(msg * n)
In [45]:
# filename: main.py
import my_func

my_func.mf_print("my_func was imported ", 3)  # my_func ¸ðµâÀÇ mf_print() ÇÔ¼ö È£Ãâ
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-45-1f9877d0ac4e> in <module>
      1 # filename: main.py
----> 2 import my_func
      3 
      4 my_func.mf_print("my_func was imported ", 3)  # my_func ¸ðµâÀÇ mf_print() ÇÔ¼ö È£Ãâ

ModuleNotFoundError: No module named 'my_func'
In [ ]:
# filename: main.py
import my_func as mf

mf.mf_print('[alias]', 5)  # mf¶ó´Â º°¸íÀ» »ç¿ëÇؼ­ ¸Þ½ÃÁö¸¦ 5ȸ ¹Ýº¹Ãâ·Â
In [ ]:
# filename: main.py
from my_func import mf_print

mf_print('-no module name-', 2)  # mf_print()¸¦ È£ÃâÇÒ ¶§ my_func.À» »ç¿ë¾ÈÇصµ µÊ
In [ ]:
# filename: main.py
from my_func import *

mf_print('-no module name-', 2)