[중첩함수]
- 함수 안에 또다른 함수가 있는 형태이다.
- 내부 함수를 밖에서 호출할 수 없다.
def out_function():
print('out function is called')
def in_function():
print('in function is called')
in_function()
in_function()
'''
Traceback (most recent call last):
File "c:\Users\Jupiter\Desktop\mygit\LearnInZeroBase\파이썬 중급\3_중첩함수.py", line 9, in <module>
in_function()
NameError: name 'in_function' is not defined. Did you mean: 'out_function'?
'''
이는 파이썬이 인터프리터 언어로서 코드를 읽어나갈 때, def out_function() 까지만 읽고 그 안은 읽지 않아서 이다.
후에 out_function()을 호출 했을 때, 비로소 함수 내부를 읽기 때문에 in_function은 호출해도 없다고 오류가 나는 것이다.
def out_function():
print('out function is called')
def in_function():
print('in function is called')
in_function()
#in_function()
out_function()
'''
out function is called
in function is called
'''
[실습1] calculator 함수를 선언하고 calculator 안에 덧셈, 뺄셈, 곱셈, 나눗셈 함수를 선언하자.
def calculator(n1,n2,operator):
def addCal():
print(f'덧셈 : {round(n1+n2,2)}')
def subCal():
print(f'뺄셈 : {round(n1-n2,2)}')
def mulCal():
print(f'곱셈 : {round(n1*n2,2)}')
def divCal():
print(f'나눗셈 : {round(n1/n2,2)}')
if operator == 1:
addCal()
elif operator == 2:
subCal()
elif operator == 3:
mulCal()
elif operator == 4:
divCal()
else:
print('wrong key')
while True:
n1 = float(input('첫번째 수 : '))
n2 = float(input('두번째 수 : '))
operator = float(input('1:덧셈,2:뺄셈,3:곱셈,4:나눗셈,5:종료'))
if operator == 5 :
print('bye~')
break
calculator(n1,n2,operator)
'''
첫번째 수 : 1
두번째 수 : 1
1:덧셈,2:뺄셈,3:곱셈,4:나눗셈,5:종료1
덧셈 : 2.0
첫번째 수 : 2
두번째 수 : 2
1:덧셈,2:뺄셈,3:곱셈,4:나눗셈,5:종료2
뺄셈 : 0.0
첫번째 수 : 3
두번째 수 : 4
1:덧셈,2:뺄셈,3:곱셈,4:나눗셈,5:종료3
곱셈 : 12.0
첫번째 수 : 4
두번째 수 : 4
1:덧셈,2:뺄셈,3:곱셈,4:나눗셈,5:종료4
나눗셈 : 1.0
첫번째 수 : 6
두번째 수 : 6
1:덧셈,2:뺄셈,3:곱셈,4:나눗셈,5:종료7
wrong key
첫번째 수 : 3
두번째 수 : 4
1:덧셈,2:뺄셈,3:곱셈,4:나눗셈,5:종료5
bye~
'''
'AboutPython' 카테고리의 다른 글
[파이썬] 모듈 사용, import, from, as 키워드 (0) | 2022.05.01 |
---|---|
[파이썬] 모듈, random 모듈을 이용한 사용자 모듈 실습 (0) | 2022.05.01 |
[파이썬] lambda 키워드 (0) | 2022.05.01 |
[파이썬] 지역변수와 전역변수, global 키워드 (0) | 2022.04.30 |
[파이썬] 인수와 매개변수, 매개변수의 개수를 모를 때 (0) | 2022.04.29 |