에러 처리
Coddy의 Python을 활용한 계산기 만들기 프로젝트 코스 레슨. 29개 중 6번째.
고려해야 할 몇 가지 가능한 오류가 있습니다.
- Division by zero -
calc('/', 3, 0)또는calc('%', 5, 0) - 잘못된 연산자 -
calc('$', 3, 2) - 잘못된 숫자 -
calc('+', 'not_a_number', 2)
챌린지
중급calc에 위 오류가 발생했을 때 예외를 발생시키는 옵션을 추가하세요.
오류 메시지는 다음 형식이어야 합니다.
calc('/', 3, 0)->Division by zerocalc('$', 3, 2)->Invalid operator "$"calc('+', [], 3)->Invalid number "[]"
Number는 int 또는 float 타입입니다.
직접 해보기
def calc(op, n1, n2):
if op == '+' or op == 'add':
return n1 + n2
if op == '-' or op == 'sub':
return n1 - n2
if op == '*' or op == 'mul':
return n1 * n2
if op == '/' or op == 'div':
return n1 / n2
if op == '%' or op == 'mod':
return n1 % n2
if op == '^' or op == 'pow':
return n1 ** n2Python을 활용한 계산기 만들기 프로젝트의 모든 레슨
직접 연습해 보세요: 온라인 Python 컴파일러