본문 바로가기

Programming

[Python][문법] 기초 - 4. 함수

반응형
#!/usr/bin/env python
# coding: utf-8

# # 1. 함수(Function)

# ### 1.1 사용자 정의 함수

# In[ ]:


def say():
    print('Hello World')
    print('Hello World')
    print('Hello World')


# In[ ]:


say()


# #### 함수의 입력값(인자)

# In[ ]:


# 입력값
def say_n( cnt ):
    for i in range(cnt):
        print(i, 'Hello World')


# In[ ]:


say_n(3)


# #### 함수의 출력값(리턴값)

# In[ ]:


# 출력값(return)
def add( a, b ):
    result = a + b
    return result


# In[ ]:


res = add( 2, 3 )
print(res)


# #### 여러개의 변수를 리턴할 수 있다

# In[ ]:


# 여러개의 출력값(return)
def add_mul( a, b ):
    result_add = a + b
    result_mul = a * b
    return result_add, result_mul


# In[ ]:


res = add_mul(3,4)
res1, res2 = add_mul(3,4)

print(res)
print(res1, res2 )


# #### 입력값: 리스트와 숫자의 차이

# In[ ]:


# 입력값: list, number
def add_lst(num1, lst1):
    num1 = num1 + 1
    lst1.append(1)


# In[ ]:


num = 1
lst = [1,2,'Hello World']
print('Before: ', num, lst)

add_lst( num, lst)
print('After : ', num, lst)


# #### Global 변수

# In[ ]:


# global 변수
def add_one(x):
    global a
    a = a + 1


# In[ ]:


a = 1
add_one(a)
print(a)


# ### 1.2 일반인자(순서), 키워드인자(변수명)

# In[ ]:


# 일반인자, 키워드인자
def sub_arg( a, b ):
    result = a - b
    return result


# In[ ]:


res1 = sub_arg( 4, 2 )
res2 = sub_arg( b = 4, a = 2 )
print(res1)
print(res2)


# ### 1.3 기본인자(Default)

# In[ ]:


# 기본인자
def circle_area(r, pi=3.14):
    area = pi * (r ** 2)
    return area


# In[ ]:


res1 = circle_area(3)
res2 = circle_area(3, 3.1415)

print('면적: {:.4f}'.format(res1))
print('면적: {:.4f}'.format(res2))


# ### 1.4 가변인자

# In[ ]:


# 가변인자
def add_many(*args):
    result = 0
    for i in args:
        result = result + i
       
    return result


# In[ ]:


add_many(1,2,3,4,5,6,7)


# In[ ]:


def add_mul(choice, *args):
    if choice == "add":
        result = 0
        for i in args:
            result = result + i
    elif choice == "mul":
        result = 1
        for i in args:
            result = result * i
           
    return result


# In[ ]:


res1 = add_mul('add', 1,2,3,4)
res2 = add_mul('mul', 1,2,3,4)

print(res1)
print(res2)


# ### 1.5 정의되지 않은 인자

# In[ ]:


# 정의되지 않은 인자
def print_kwargs(**kwargs):
    print(kwargs)


# In[ ]:


print_kwargs(a=1)
print_kwargs(name='foo', age=3)


# In[ ]:


def area_arg(r, *pi, **info):
    for item in pi:
        area = item * (r ** 2)
        print('반지름: ', r, 'PI: ', item, '면적: ', round(area,2) )
       
    for key in info:
        print(key, ':', info[key])


# In[ ]:


area_arg(3, 3.14, 3.1415, line_color='파랑', area_color='노랑')

print()

area_arg(5, 3.14, 3.1415, polygon_name='원', value='면적')


# #### <참고> tuple, dict의 활용

# In[ ]:


def f_a(a,b,c):
    print(a,b,c)


# In[ ]:


def f_b(a,b,c):
    print(a,b,c)
   


# In[ ]:


lst = [1,2,3]
f_a(*lst)


# In[ ]:


dic = {'a':4, 'b':5, 'c':6}
f_b(**dic)


# ### 1.6 익명함수( lambda )

# In[ ]:


add = lambda a, b: a + b
result = add(3, 4)
print(result)


# In[ ]:


def f_c( a, b, func ):
    result = func(a,b)
    return result


# In[ ]:


res = f_c(2,3, lambda x, y: x + y )
print(res)


# ### 1.7 예제: 요일 구하기(함수)

# In[ ]:


# 년월일을 입력받는 함수
# 반환값: 년월일을 튜플형태로 반환
def input_date():
    year  = int(input('년도를 입력하시오: '))
    month = int(input('월을 입력하시오: '))
    day   = int(input('일을 입력하시오: '))
   
    return year, month, day


# In[ ]:


# 윤년인지를 확인하는 함수
# 입력인자: year
# 반환값: Ture = 윤년, False = 평년
def is_leap(year):
    if year % 400 == 0:                 # 400으로 나뉘는 해: 윤년
        return True
    elif year % 100 == 0:               # 100으로 나뉘는 해: 평년
        return False
    elif year % 4 == 0:                 # 4으로 나뉘는 해  : 윤년
        return True
    else:
        return False


# In[ ]:


# 요일을 구하는 함수
# 입력인자: year, month, day
# 반환값: 요일
def get_day_name(year, month, day):

    total_days = 0

    year_month_days = [0,31,28,31,30,31,30,31,31,30,31,30,31]
    day_names = ['일요일','월요일','화요일','수요일','목요일','금요일','토요일']
   
    for item in range(1,year):
        if is_leap(item):
            total_days = total_days + 366
        else:
            total_days = total_days + 365

    for item in range(1,month):
        total_days = total_days + year_month_days[item]

    if month >= 3:
        if is_leap(year):
            total_days = total_days + 1
        else:
            total_days = total_days + 0

    total_days += day
    remainder = total_days % 7
   
    return day_names[remainder]


# In[ ]:


# main

year, month, day = input_date()
day_name = get_day_name(year, month, day)

print(day_name, '입니다')


# ### 1.8 예제: 성적 처리 시스템(함수)

# In[ ]:


# 학생들의 총점을 구하는 함수
def calculate_total(students):
    for student in students:
        student['total'] = student['kor'] + student['eng'] + student['math']


# In[ ]:


# 학생들의 평균을 구하는 함수
def calculate_average(students):
    for student in students:
        student['avg'] = student['total'] / len(students)


# In[ ]:


# 학생들의 등수를 구하는 함수
def calculate_order(students):
    temp_students = sorted(students, key = lambda x: x['total'], reverse=True) # 익명함수 활용
    order = 1
    for student in temp_students:
        student['order'] = order
        order = order + 1
   
    return temp_students


# In[ ]:


# 반 평균을 구하는 함수
def calculate_class_avg(students):
    class_total = 0
   
    for student in students:
        class_total = class_total + student['total']
       
    return class_total / len(students)


# In[ ]:


# 반의 국어 평균을 구하는 함수
def calculate_kor_avg(students):
    kor_total = 0
   
    for student in students:
        kor_total = kor_total + student['kor']
       
    return kor_total / len(students)


# In[ ]:


# 반의 영어 평균을 구하는 함수
def calculate_eng_avg(students):
    eng_total = 0
   
    for student in students:
        eng_total = eng_total + student['eng']
       
    return eng_total / len(students)


# In[ ]:


# 반의 수학 평균을 구하는 함수
def calculate_math_avg(students):
    math_total = 0
   
    for student in students:
        math_total = math_total + student['math']
       
    return math_total / len(students)


# In[ ]:


# 학생 데이터를 출력하는 함수
def print_student(students):
    for student in students:
        print('번호: {:s}, 이름: {:s}, 국어: {:d}, 영어: {:d}, 수학: {:d}, 총점: {:d}, 평균: {:.2f}, 등수: {:d}'.format(
               student['num'], student['name'],
               student['kor'], student['eng'], student['math'],
               student['total'], student['avg'], student['order'])
             )


# In[ ]:


# 반의 평균 및 각 과목의 평균을 출력하는 함수
def print_class(class_avg, kor_avg, eng_avg, math_avg):
    print('반 평균  : {:.2f}'.format(class_avg))
    print('국어 평균: {:.2f}'.format(kor_avg)  )
    print('영어 평균: {:.2f}'.format(eng_avg)  )
    print('수학 평균: {:.2f}'.format(math_avg) )


# In[ ]:


# main

students = [
               {'num':'1','name':'김철수','kor':90,'eng':80,'math':85,'total':0,'avg':0.0,'order':0 },
               {'num':'2','name':'박제동','kor':90,'eng':85,'math':90,'total':0,'avg':0.0,'order':0 },
               {'num':'3','name':'홍길동','kor':80,'eng':80,'math':80,'total':0,'avg':0.0,'order':0 }
           ]

class_avg   = 0.0
kor_avg     = 0.0
eng_avg     = 0.0
math_avg    = 0.0

calculate_total(students)                      # 학생의 총점 계산
calculate_average(students)                    # 학생의 평균 계산
students = calculate_order(students)           # 학생의 등수 계산

class_avg   = calculate_class_avg(students)    # 반 평균 계산
kor_avg     = calculate_kor_avg(students)      # 반 국어 평균 계산
eng_avg     = calculate_eng_avg(students)      # 반 영어 평균 계산
math_avg    = calculate_math_avg(students)     # 반 수학 평균 계산


print_student(students)                            # 학생들 데이터 출력
print()
print_class(class_avg, kor_avg, eng_avg, math_avg) # 반 평균, 각 과목 평균 출력


# ### 1.9 내장 함수(Built-in 함수)

# [내장함수 참조 사이트](https://docs.python.org/3.4/library/functions.html)

# #### abs()

# In[ ]:


abs(3)
abs(-3)
abs(-1.2)


# #### all()

# In[ ]:


all([1, 2, 3])
all([1, 2, 3, 0])


# #### any()

# In[ ]:


any([1,2,3,0])
any([0,''])


# #### enumerate()

# In[ ]:


for i, name in enumerate(['body', 'foo', 'bar']):
    print(i, name)


# #### isinstance()

# In[ ]:


isinstance(1, int)


# #### len()

# In[ ]:


len("python")
len([1,2,3])
len((1, 'a'))


# #### map()

# In[ ]:


def two_times(x):
    return x*2

list(map(two_times, [1, 2, 3, 4]))


# #### max()

# In[ ]:


max([1, 2, 3])
max("python")


# #### min()

# In[ ]:


min([1, 2, 3])
min("python")


# #### pow()

# In[ ]:


pow(2, 3)


# #### range()

# In[ ]:


list(range(5))
list(range(5, 10))
list(range(1, 10, 2))


# #### round()

# In[ ]:


round(4.6)
round(5.678, 2)


# #### sorted()

# In[ ]:


sorted([3, 1, 2])
sorted(['a', 'c', 'b'])
sorted("zero")
sorted((3, 2, 1))


# In[ ]:


lst = [3, 1, 2]
lst.sort()


# #### sum()

# In[ ]:


sum([1,2,3])
sum((4,5,6))


# #### type()

# In[ ]:


type("abc")
type([ ])


# #### zip()

# In[ ]:


list(zip([1, 2, 3], [4, 5, 6]))
list(zip([1, 2, 3], [4, 5, 6], [7, 8, 9]))
list(zip("abc", "def"))


# ### 1.10 외장 함수

# #### math

# In[ ]:


import math
math.sin(math.pi)
math.log(math.e)


# In[ ]:


import math as ma
ma.sin(ma.pi)
ma.log(ma.e)


# In[ ]:


from math import sin, log, pi, e
sin(pi)
log(e)


# In[ ]:


from math import *
sin(pi)
log(e)


# #### os

# In[ ]:


import os


# In[ ]:


os.name


# In[ ]:


# os.environ


# In[ ]:


os.environ['PATH']


# In[ ]:


os.getcwd()


# In[ ]:


# os.chdir("/home/fdnx")


# In[ ]:


os.path.join(os.getcwd(), 'tmp')


# In[ ]:


os.listdir('c:\\')
#os.listdir('/home/fdnx')


# In[ ]:


os.mkdir( os.path.join(os.getcwd(), 'test'))
os.listdir()


# In[ ]:


os.remove( os.path.join(os.getcwd(), 'aaa.txt'))
os.listdir()


# In[ ]:


os.rmdir( os.path.join(os.getcwd(), 'test'))
os.listdir()


# In[ ]:


os.system("dir")


# In[ ]:


f = os.popen("dir")
print(f.read())


# #### sys

# In[ ]:


import sys


# In[ ]:


sys.argv


# In[ ]:


for item in sys.argv:
    print(item)


# In[ ]:


sys.copyright


# In[ ]:


sys.version


# In[ ]:


sys.path


# In[ ]:


sys.path.append("/home/fdnx")

# export PYTHONPATH="${PYTHONPATH}:/my/other/path"


# #### time

# In[ ]:


import time


# In[ ]:


time.time()


# In[ ]:


time.sleep(1)


# In[ ]:


input('Enter a number: ')
t1 = time.time()
time.sleep(3)

input('Enter a number again: ')
t2 = time.time()

time_gap = t2 -t1

print('Time gap: ', time_gap)


# In[ ]:


get_ipython().run_line_magic('time', "print('aa')")
# %timeit print('aa')


# In[ ]:


get_ipython().run_cell_magic('time', '', "print('aa')\ntime.sleep(2)\nprint('bb')\n#%%timeit\n#print('aa')\n#print('bb')")


# In[ ]:


time.gmtime()


# In[ ]:


time.localtime()


# In[ ]:


time.asctime(time.localtime())


# In[ ]:


time.mktime(time.localtime())


# #### datetime

# In[ ]:


import datetime as dtime


# In[ ]:


dtime.date.today()


# In[ ]:


dtime.date.fromtimestamp(time.time())


# In[ ]:


from datetime import datetime


# In[ ]:


dt = datetime(2011, 10, 29, 20, 30, 21)


# In[ ]:


dt.day


# In[ ]:


dt.minute


# In[ ]:


dt.date()


# In[ ]:


dt.time()


# In[ ]:


dt.strftime('%Y-%m-%d %H:%M:%S')


# In[ ]:


datetime.strptime('20191031092030', '%Y%m%d%H%M%S')


# In[ ]:


datetime.strptime('20091031', '%Y%m%d')


# In[ ]:


dt.replace(minute=0, second=0)


# In[ ]:


dt2 = datetime(2011, 11, 15, 22, 30)
delta = dt2 - dt
delta
type(delta)


# In[ ]:


dt


# In[ ]:


dt + delta


# [날짜 및 시간 문자열 포멧 참조 사이트](https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior)

# <center>날짜 및 시간 지정 | <center> 문자열 의미
# :---:|:---
# %Y | 앞의 빈자리를 0으로 채우는 4자리 연도 숫자
# %m | 앞의 빈자리를 0으로 채우는 2자리 월 숫자
# %d | 앞의 빈자리를 0으로 채우는 2자리 일 숫자
# %H | 앞의 빈자리를 0으로 채우는 24시간 형식 2자리 시간 숫자
# %M | 앞의 빈자리를 0으로 채우는 2자리 분 숫자
# %S | 앞의 빈자리를 0으로 채우는 2자리 초 숫자
# %A | 영어로 된 요일 문자열
# %B | 영어로 된 월 문자열

# In[ ]:


from dateutil.parser import parse


# In[ ]:


parse('2016-04-16')


# In[ ]:


parse("Apr 16, 2016 04:05:32 PM")


# In[ ]:


parse('6/7/2016')


# #### random

# In[ ]:


import random


# In[ ]:


random.seed(123)


# In[ ]:


random.randint(1,10)


# In[ ]:


random.random()


# In[ ]:


# lotto_number

import random

def get_lotto_numbers():
    lotto_numbers = []
   
    while True:
        if len(lotto_numbers) == 6:
            break
       
        number = random.randint(1,45)
        if number in lotto_numbers:
            continue
        else:
            lotto_numbers.append(number)
       
    return sorted(lotto_numbers)


# In[ ]:


lotto_numbers = get_lotto_numbers()
print(lotto_numbers)


# ### 1.11 라이브러리(패키지)

# #### package, module, function

# #### mod1.py
#
# ```python
# def add(a, b):
#     return a+b
#
# def sub(a, b):
#     return a-b
# ```

# #### mod2.py
#
# ```python
# PI = 3.141592
#
# def add(a, b):
#     return a+b
#
# def sub(a, b):
#     return a-b
#
# if __name__ == "__main__":
#     print(add(3, 4))
#     print(sub(5, 3))
# ```

# In[ ]:


import mod1


# In[ ]:


mod1.add(2,3)


# In[ ]:


import mod2


# In[ ]:


mod2.add(mod2.PI, 3)


# #### <참고> sys.path, sys.path.append, PYTHONPATH 환경 변수

# #### <참고>pip install package_name

# ### 1.12 예제: 숫자 맞추기 게임

# In[ ]:


import random

number = random.randint(1,100)
ans = None

while True:
    print('종료하려면 quit를 입력하세요')
   
    ans = input('1 ~ 100 사이의 숫자를 선택하시오: ')
   
    # 프로그램 종료 체크
    if ans == 'q' or ans == 'quit' or ans == 'exit':
        print('프로그램을 종료합니다.')
        break
       
    # 숫자를 입력했는지 체크
    if not ans.isdecimal():
        print('{}은 잘못된 입력입니다.!!!'.format(ans))
        continue
   
    # 입력값을 숫자로 변환
    num = int(ans)
   
    # 1 ~ 100 사이의 숫자인지 체크
    if num < 1 or num >100:
        print('{}는 1 ~ 100 사이의 숫자가 아닙니다'.format(num))
        continue
   
    # 정답 체크
    if num == number:
        print('축하합니다.')
        print('정답입니다 ==> {}'.format(num))
        print('프로그램을 종료합니다.')
        break
   
    if num > number:
        print('정답은 {}보다 작은수 입니다.'.format(num))
        continue
       
    if num < number:
        print('정답은 {}보다 큰수 입니다.'.format(num))
        continue
       


# ---

# In[ ]:


# end of file


# In[ ]:



반응형
LIST