Menu
Coddy logo textTech

Basic structure

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

The next step is to evaluate list of expressions.

The basic structure is - [op, num1, num2]

Some examples:

  • ['+', 1, 2]  ->  calc('+', 1, 2)
  • ['*', 3, 2]  ->  calc('*', 3, 2)
  • ['/', 5.3, 0]  ->  calc('/', 5.3, 0)
challenge icon

Challenge

Easy

create function eval which gets basic structure, a list as described above, and returns the calculation result.

Use the calc function you created!

Try it yourself

def calc(op, n1, n2=None):
    if not isinstance(n1, int) and not isinstance(n1, float):
        raise Exception('Invalid number "' + str(n1) + '"')

    if n2 is None:
        if op == '+' or op == 'add':
            return n1
        if op == '-' or op == 'sub':
            return -n1

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

    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