반복적인 코드를 묶어서 사용하는 방법 > 코드의 유지보수가 쉬워진다
def, return, argument, parameter, docstring, scope, lambda
사용법 : 함수선언(코드작성) > 함수호출(코드실행)
# 1. 로또번호출력
lotto = []
while True:
random_number = random.randint(1, 45)
lotto.append(random_number)
lotto = list(set(lotto))
if len(lotto) >= 6:
break
lotto.sort()
print(lotto)
# 파이썬출력
print('python')
# 로또번호출력
lotto = []
while True:
random_number = random.randint(1, 45)
lotto.append(random_number)
lotto = list(set(lotto))
if len(lotto) >= 6:
break
lotto.sort()
print(lotto)
[2, 11, 16, 36, 42, 44]
[3, 6, 11, 17, 27, 28]
============================
# 함수 사용 후
#2. 함수선언
def display_lotto():
lotto = []
while True:
random_number = random.randint(1, 45)
lotto.append(random_number)
lotto = list(set(lotto))
if len(lotto) >= 6:
break
lotto.sort()
print(lotto)
# 로또번호출력
display_lotto()
# 파이썬출력
print('python')
# 로또번호출력
display_lotto()
>>>
[7, 22, 30, 31, 33, 37]
python
[7, 24, 34, 38, 43, 44]
함수를 사용하면 함수를 호출해 이미 만들어 놓은 함수로 바로 사용할 수 있다.
# 함수선언(코드작성)
def display_lotto():
lotto = []
while True:
random_number = random.randint(1, 45)
lotto.append(random_number)
lotto = list(set(lotto))
if len(lotto) >= 6:
break
lotto.sort()
print(lotto)
# 함수호출(코드실행)
display_lotto()
# 함수선언(코드작성)
def display_lotto(count): # count : parameter
lotto = []
while True:
random_number = random.randint(1, 45)
lotto.append(random_number)
lotto = list(set(lotto))
if len(lotto) >= count:
break
lotto.sort()
print(lotto)
# 로또번호출력 : 6개
display_lotto(6) # 6 : argument
# 로또번호출력 : 7개
display_lotto(7)
[7, 8, 12, 14, 16, 22]
[2, 14, 15, 16, 36, 43, 45]
# 여러개의 argument와 parameter를 사용할 수있다.
# 단, parameter와 argument의 갯수가 같아야 실행 될 수 있다.
# 그러나 default parameter를 사용하면 값이 하나라도 실행이 된다
# keyword argument : argument 중 원하는 변수에 값을 주고 싶을 때 쓰는 것
def plus(n1, n2=10, n3=20): # n1, n2 : parameter, n2=10, n3=20 : default parameter
print(n1 + n2 + n3)
# 함수호출(코드실행)
plus(1, 2) # 1, 2 : argument
plus(1)
plus(1,10, 100)
plus(1, n3=100) # n3=100 : keyword argument
>>>23
31
111
111
=====================
# 숫자의 범위와 숫자의 갯수를 아규먼트로 설정해서 함수를 호출할 수 있도록 함수를 수정
# display_lotto를 호출할 때 파라미터가 없으면 1 ~ 45까지 6개의 숫자를 출력
def display_lotto(count=6, end=45): # count : parameter
lotto = []
while True:
random_number = random.randint(1, end)
lotto.append(random_number)
lotto = list(set(lotto))
if len(lotto) >= count:
break
lotto.sort()
print(lotto)
display_lotto() # 1 ~ 45까지 6개의 숫자
display_lotto(end=50, count=10) # 1 ~ 50까지 10개의 숫자, 변수명으로 들어가면 순서 바뀌어도 괜찮음
display_lotto(15, 47) # 키워드입력 없으면 순서대로 들어가야한다.
[2, 16, 22, 33, 43, 45]
[5, 7, 11, 23, 26, 32, 36, 39, 40, 50]
[3, 4, 5, 6, 12, 16, 22, 25, 26, 28, 32, 33, 41, 44, 46]
# 리턴이 있는 함수 예시 : str.upper()
# data 내용 자체는 변화 시키지 않고 결과값을 반환해 준다
data = 'python'
result = data.upper()
print(data,result)
>>>python PYTHON
# 리턴이 없는 함수 예시
# 데이터 자체를 바꿔주고 결과값에는 값이 없다.
data = [1, 3, 2]
result = data.sort()
print(data, result)
[1, 2, 3] None
# 함수의 코드 실행 중단
# 만약 return이 아니라 break 였다면 'Done'이 출력됐을 것임
# 하지만 return을 만나면 바로 함수를 멈추어서 시간 절약함.
def echo(msg, count=3):
for idx in range(count):
if idx >= 5:
return
print(msg)
print('Done')
echo('python', 7)
python
python
python
python
python
# 여러개의 데이터를 리턴
# 컬렉션을 써서 작성해야 한다.
def calc(n1, n2):
result = [n1 + n2, n1 - n2]
return result
result = calc(3, 1)
result
# 다른 코드의 경우 따로 출력하고 싶다면 아래와 같이 작성해야한다.
plus = result[0]
minus = result[1]
plus, minus
(4, 2)
# 여러개의 데이터를 리턴
# 파이썬의 경우
#튜플로 나오기 때문에 여러개의 데이터를 여러개의 변수에 한번에 저장 가능하다.
def calc(n1, n2):
return n1 + n2, n1 - n2
plus, minus = calc(3, 1)
plus, minus
(4, 2)
def calc(n1, n2):
return n1 + n2, n1 - n2
plus, _ = calc(3, 1) # 특정값이 필요 없을 경우 _로 넣는다
plus
4
def plus(n1, n2):
'''
# 함수설명
This function is to plus two numbers.
# parameter 설명
parameter
--------------
n1 : int, float : firts number
n2 : int, float : second number
#
return
--------------
n1 + n2 : int, float
'''
return n1 + n2
# docstring 보는 법 : ctrl + space, help() 함수 사용
help(plus)
Help on function plus in module __main__:
plus(n1, n2)
# 함수설명
This function is to plus two numbers.
# parameter 설명
parameter
n1 : int, float : firts number
n2 : int, float : second number
#
return
n1 + n2 : int, float
help(print)
Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
print('A', 'B')
print('A', 'B', sep=', ', end='\t')
print('C', 'D')
A B
A, B C D
def plus(*args): # parameter에 컬렉션 데이터 타입을 받아줌 : 식별자1개, 데이터 n개
print(type(args), args)
#return n1 + n2
plus(1, 2, 3, 4, 5) # 여러개의 argument
>>> <class 'tuple'> (1, 2, 3, 4, 5)
========================
def plus(*args, **kwargs): # parameter에 컬렉션 데이터 타입을 받아줌 : 식별자1개, 데이터 n개
print(type(args), args)
print(type(kwargs), kwargs)
#return n1 + n2
# 항상 키워드 아규먼트는 키워드가 없는 아규먼트 뒤에 사용해야한다.
# 항상 default parameter는 default 값이 없는 parameter 뒤에 사용해야 한다.
plus(1, 2, 3, 4, 5, n1=10, n2=30, n3=40) # 여러개의 argument
>>>
<class 'tuple'> (1, 2, 3, 4, 5)
<class 'dict'> {'n1': 10, 'n2': 30, 'n3': 40}
========================
def plus(*args, **kwargs): # 파라미터에 컬렉션 데이터 타입을 받아줌 : 식별자1개, 데이터n개
print(type(args), args)
print(type(kwargs), kwargs)
return sum(args) + sum(kwargs.values())
# 키워드 아규먼트는 키워드가 없는 아규먼트 뒤에 사용
# 디폴트 파라미터는 디폴트 값이 없는 파라미터 뒤에 사용
plus(1, 2, 3, 4, 5, n1=10, n2=30) # 여러개의 아규먼트
>>><class 'tuple'> (1, 2, 3, 4, 5)
<class 'dict'> {'n1': 10, 'n2': 30}
55
=================
data = {'num1': 10, 'num2': 20}
data.keys(), data.values()
>>>
(dict_keys(['num1', 'num2']), dict_values([10, 20]))
====================
# *args, **kwargs : 아규먼트에서 사용
# parameter 사용 : 여러개의 argument > 컬렉션 데이터 타입(tuple, dict)으로 묶어줌
# argument 사용 : 컬렉션 데이터 타입(list, tuple, dict) > 여러개의 아규먼트로 풀어줌
=======================
# * : 리스트 대괄호를 풀어주는 기능
def echo(*args, **kwargs):
print(type(args), args)
print(type(kwargs), kwargs)
data = [1, 2, 3]
echo(data) # echo([1, 2, 3]) > 아규먼트 1개, 데이터 타입 : list
echo(*data) # echo(1, 2, 3) > 아규먼트 3개, 데이터 타입 : 정수
>>>
# * : 리스트 대괄호를 풀어주는 기능
def echo(*args, **kwargs):
print(type(args), args)
print(type(kwargs), kwargs)
data = [1, 2, 3]
echo(data) # echo([1, 2, 3]) > 아규먼트 1개, 데이터 타입 : list
echo(*data) # echo(1, 2, 3) > 아규먼트 3개, 데이터 타입 : 정수
<class 'tuple'> ([1, 2, 3],)
<class 'dict'> {}
<class 'tuple'> (1, 2, 3)
<class 'dict'> {}
======================
# ** : dict의 중괄호를 풀어주는 기능
data = {'num1' : 10, 'num2' : 20}
echo(data) # echo({'num1' : 10, 'num2' : 20}) > 아규먼트 1개, 데이터타입 : 딕셔너리
echo(**data) # echo(num1=10, num2=20) > 키워드 아규먼트 2개, 데이터타입 : 정수
>>>
<class 'tuple'> ({'num1': 10, 'num2': 20},)
<class 'dict'> {}
<class 'tuple'> ()
<class 'dict'> {'num1': 10, 'num2': 20}
args, **kwargs
parameter
-. 여러개의 아규먼트 > 하나의 컬렉션 데이터타입(tuple, dict)으로 묶어서 받아줌
-. args : 키워드가 없는 여러개의 아규먼트를 받음 :tuple
-. kwargs : 키워드가 있는 여러개의 아규먼트를 받음 : dict
argument
-. 묶여있는 컬렉션 데이터타입(list, tuple, dict) > 여러개의 아규먼트로 풀어서 함수 호출
-. *args : list, tuple 데이터 타입의 데이터를 여러개의 키워드가 없는 아규먼트로 풀어줌
-. kwargs : dict 데이터 타입의 데이터를 여러개의 키워드가 있는 아규먼트로 풀어줌
ef connect(**kwargs):
print('connect : ', kwargs['host'], kwargs['user'], kwargs['pw'])
============
data = {'host' : '1.2.3.5', 'user' : 'python', 'pw' : '1234'}
# connect(host='1.2.3.4', user='python', pw='1234')
# 아규먼트가 많을 때 한번에 모두 바꿀 수 있다.
connect(host=data['host'], user=data['user'], pw=data['pw'])
connect(host=data['host'], user=data['user'], pw=data['pw'])
>>>
connect : 1.2.3.5 python 1234
connect : 1.2.3.5 python 1234
=============
data = {'host' : '1.2.3.5', 'user' : 'python', 'pw' : '1234'}
# connect(host=data['host'], user=data['user'], pw=data['pw'])
# 아규먼트가 많을 때 한번에 모두 바꿀 수 있다. 더 빠르고 간편하게 수정 가능함.
# 쉬운 난이도가 아님
connect(**data)
connect(**data)
connect(**data)
>>>
connect : 1.2.3.5 python 1234
connect : 1.2.3.5 python 1234
connect : 1.2.3.5 python 1234
- 함수 밖 : 전역영역 : global : 함수 밖에서 변수가 선언되는 경우
- 함수 안 : 지역영역 : local
# global : 지역영역에서 전역영역의 변수사용 방법
data = 10 # global
def change():
global data # global영역의 변수를 가지고 오는 것임.
data = 20 # 변수의 저장공간을 같은 저장공간을 사용하게 됨
print(data)
change()
print(data)
>>>
20
20
=============
# 지역영역에서 사용되는 변수(식별자)는 지역영역에 없으면, 전역영역의 변수를 가져와서 사용함.
data = 10
def change():
print('local', data)
change()
print('global', data)
>>>
local 10
globald 10
=================
# return : 전역영역에서 지역영역의 변수 사용하는 방법
data = 10
def change():
data = 20
return data
data = change()
print(data)
>>> 20
============
data = 10 # 몇중으로 쌓여있더라도 전역의 data가 적용 된다.
def change1():
data = 20
def change2():
global data
print('local', data)
change2()
change1()
>>> 10
# 함수는 데이터 타입이 function인 변수이다.
# function은 코드를 담고 있는 데이터타입이다.
# 함수는 코드를 실행할 수 있는 특징을 가진 변수이다.
type(plus), plus(1, 2)
>>>(function, 3)
===================
함수도 변수이기 때문에 argument와 parameter로 사용 될 수 있다
# 변수 3개 선언 : plus, minus, calc : 저장공간 3칸 사용
def plus(n1, n2):
return n1 + n2
def minus(n1, n2):
return n1 - n2
def calc(func, n1, n2): # func: plus
return func(n1, n2)
# 함수에서 다른 함수를 사용해야할 때 사용한다.
calc(plus, 1, 2), calc(minus, 1, 2)
>>> (3, -1)
=====================================
- 간단한 함수를 함수 선언 없이 사용 가능
- **lambda 변수, 변수 : 함수식**
- 일회용 함수라고 생각하면 편함
func = lambda n1, n2: n1 + n2
func(1, 2)
>>> 3
===============
# calc 변수 1개 : 저장공간 1칸 사용
# 실제 lambda 함수 많이 사용한다.
def calc(func, n1, n2):
return func(n1, n2)
calc(lambda n1, n2: n1 + n2, 1, 2), calc(lambda n1, n2: n1 - n2, 1, 2)
>>>(3, -1)
# 실수 할만한 코드 3
# -. 식별자는 같지만 동작하는 영역이 다르기 때문에 .local 영역의
# 변수 값은 global 영역에는 영향을 주지 못한다.
data = 10 # global
def change():
data = 20 # local : 식별자만 같지 저장 공간은 다른 곳을 써서 데이터 값이 변하지 않음.
print(data)
change()
print(data)
>>>
20
10
느낀점 : 지금 시장에 나와있는 건 99% 기초 책이라고 생각 그래서 책으로 기본을 다지고 공식 문서를 통해 공부하는 것이 좋다.
근데 어렵다