Menu
Coddy logo textTech

Handling errors

Lesson 6 of 29 in Coddy's Calculator project using Python course.

There are some possible errors we should consider,

  • Division by zero - calc('/', 3, 0) or calc('%', 5, 0)
  • Invalid operator - calc(', 3, 2)
  • Invalid number - calc('+', 'not_a_number', 2)
challenge icon

Challenge

Medium

Add to calc option to raise an exceptions when the above errors happen.

The error messages should be in the following formats,

  • calc('/', 3, 0)  ->  Division by zero
  • calc(', 3, 2)  ->  Invalid operator "$"
  • calc('+', [], 3)  ->  Invalid number "[]"

Number is of type int or float

Try it yourself

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 ** n2

All lessons in Calculator project using Python