Menu
Coddy logo textTech

Single number

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

Currently the calc function supports only two numbers operations.

Let's add single number operations for '+' and '-',

  • calc('+', 5.4)  ->  5.4
  • calc('-', 3)  ->  -3
challenge icon

Challenge

Easy

Add support for single number operators for '+' and '-'.

  • Add default value, None, to the 3rd argument of calc

Try it yourself

def calc(op, n1, n2):
    if not isinstance(n1, int) and not isinstance(n1, float):
        raise Exception('Invalid number "' + str(n1) + '"')
    if not isinstance(n2, int) and not isinstance(n2, float):
        raise Exception('Invalid number "' + str(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':
        if n2 == 0:
            raise Exception("Division by zero")
        return n1 / n2
    if op == '%' or op == 'mod':
        if n2 == 0:
            raise Exception("Division by zero")
        return n1 % n2
    if op == '^' or op == 'pow':
        return n1 ** n2

    raise Exception('Invalid operator "' + op + '"')

All lessons in Calculator project using Python