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