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):
pri
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
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.