-
[파이썬] 8. 파이썬 함수 정의와 호출 - 변수의 범위 (지역변수와 전역변수), 가변길이 인자 (*args, **kwargs), format 함수파이썬 Python 2019. 12. 4. 13:36
# 변수의 범위 (variable scope)
- 변수가 참조 가능한 코드상의 범위를 명시
- 함수 내 변수는 자신이 속한 코드 블록이 종료되면 소멸됨 (코드블록 내에서만 유효)
- 이렇게 특정 코드블록에서 선언된 변수를 "지역변수 (local variable)" 라고 함
- 반대로 프로그램 종료 전까지 유지되는 변수는 "전역변수 (global variable)"
- 같은 이름의 지역변수와 전역변수가 있을 경우, 지역변수의 우선순위가 더 높음
num1 = 10 num2 = 20 #num1, num2는 글로벌 변수, 전역변수 def test(num1, num2): #num1, num2 는 지역변수, 로컬변수 print(num1, num2) return num1+num2 test(32 ,40) print(num1, num2)
# 가변길이 인자 (variable length argument)
전달되는 파라미터의 개수가 고정적이지 않은 경우
ex) print(), format()
- *args : 파라미터를 튜플의 형태로 전달
- **kwargs: 파라미터를 딕셔너리 형태로 전달 (named parameter)
print() print(1) print(1, 2) print(1, 2, 3) print(1, 2, 4 , 5) def test(*args): for item in args: print(item) print(type(args)) test(10, 20, 30, 100) ''' 1 1 2 1 2 3 1 2 4 5 10 20 30 100 <class 'tuple'> '''
# keyword parameter (키워드 파라미터)
- **가 붙은 경우 키워드 파라미터로 인식
- 즉, 함수 호출시에 파라미터 이름과 값을 함께 전달 할 수 있음
def test2(**kwards): #key word arguments for key, value in kwards.items(): print('key: ', key, ', value: ', value) print(type(kwards)) test2(a =1, b=2, c=4, name = 'bob', ddd = 'w') ''' key: a , value: 1 key: b , value: 2 key: c , value: 4 key: name , value: bob key: ddd , value: w <class 'dict'> '''
- 가변길이 함수의 대표적인 예는 문자열 포맷(format) 함수
- 여러가지 값과 포맷을 이용하여 문자열을 정의할 수 있는 함수
- {} placeholder를 문자열 내에 위치시킨후,
- 해당위치에 format 함수로 전달 된 값으로 대체해 문자열 구성
- 포맷 구성: https://pyformat.info/
PyFormat: Using % and .format() for great good!
Python has had awesome string formatters for many years but the documentation on them is far too theoretic and technical. With this site we try to show you the most common use-cases covered by the old and new style string formatting API with practical exam
pyformat.info
a = '오늘 온도: {today_temp}도, 강수 확률은: {today_prob}%, 내일온도: {tomorrow_temp}도'.format(today_temp=20, today_prob = 50,tomorrow_temp = 23) print(a)
반응형'파이썬 Python' 카테고리의 다른 글
[파이썬] 10. numpy 모듈 _ ndarray (0) 2019.12.23 [파이썬] 9. Lamda 함수란? filter, map, reduce (0) 2019.12.05 [파이썬] 7. 파이썬 함수 정의와 호출 - 함수의 parameter, return (함수 파라미터와 리턴) (0) 2019.12.04 [파이썬] 6. 반복문 while / for 의 이해 (feat. break와 continue) (1) 2019.11.25 [파이썬] 5. 조건문 if / elif/ else (0) 2019.11.25