Using a dictionary as a switch statement in Python

dictionary, python

Solution

Define your dictionary like pairs of the form `str : function`:

my_dict = {'+' : add, 
           '-' : sub, 
           '*' : mult, 
           '/' : div}

And then if you want to call an operation, use `my_dict[op]` to get a function, and then pass call it with the corresponding parameters:

 my_dict[op] (part1, part3)
|___________|
      |
  function (parameters)

Note: Don't use Python built-in names as names of variables, or you will hide its implementation. Use `my_dict` instead of `dict` for example.

Problem

I'm trying to make a simple calculator in Python, using a dictionary. Here's my code: ``` def default(): print "Incorrect input!" def add(a, b): print a+b def sub(a, b): print a-b def mult(a, b): print a*b def div(a, b): print a/b line = raw_input("Input: ") parts = line.split(" ") part1 = float(parts[0]) op = parts[1]; part3 = float(parts[2]) dict = { '+': add(part1, part3), '-': sub(part1, part3), '*': mult(part1, part3), '/': div(part1, part3) } try: dict[op] except KeyError: default() ``` but all the functions are activated. What's the problem?

Original source

Related problems