Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a dictionary as a switch statement in Python

Tags:

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?

like image 387
user3342163 Avatar asked Feb 23 '14 00:02

user3342163


People also ask

Can you use a dictionary as a key in Python?

A dictionary or a list cannot be a key. Values, on the other hand, can literally be anything and they can be used more than once.

What is a switch statement in Python?

What is a Switch Statement in Python? In general, the switch is a control mechanism that tests the value stored in a variable and executes the corresponding case statements. Switch case statement introduces control flow in your program and ensures that your code is not cluttered by multiple 'if' statements.

Is there a switch equivalent in Python?

From version 3.10 upwards, Python has implemented a switch case feature called “structural pattern matching”. You can implement this feature with the match and case keywords.


2 Answers

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.

like image 120
Christian Tapia Avatar answered Oct 03 '22 10:10

Christian Tapia


It is because when the dictionary is populated, it executes each operation with the operands, and at the end, you're calling dict[op] which contains None and do nothing with it.

What happens is:

# N.B.: in case this is not clear enough,  #       what follows is the *BAD* code from the OP #       with inline explainations why this code is wrong  dict = {     # executes the function add, outputs the result and assign None to the key '+'     '+': add(part1, part3),      # executes the function sub, outputs the result and assign None to the key '-'     '-': sub(part1, part3),     # executes the function mult, outputs the result and assign None to the key '*'     '*': mult(part1, part3),     # executes the function div, outputs the result and assign None to the key '/'     '/': div(part1, part3)     }  try:     # gets the value at the key "op" and do nothing with it     dict[op] except KeyError:     default() 

which is why you get all outputs, and nothing happens in your try block.

You may want to actually do:

dict = {     '+': add,     '-': sub,     '*': mult,     '/': div     }  try:     dict[op](part1, part3) except KeyError:     default() 

but as @christian wisely suggests, you should not use python reserved names as variable names, that could lead you into troubles. And another improvement I advice you todo is to print the result once, and make the functions lambdas:

d = {     '+': lambda x,y: x+y,     '-': lambda x,y: x-y,     '*': lambda x,y: x*y,     '/': lambda x,y: x/y     }  try:     print(d[op](part1, part3)) except KeyError:     default() 

which will return the result and print it

like image 43
zmo Avatar answered Oct 03 '22 08:10

zmo