Simple Calculator in Python
Pick an operator, apply it to two numbers and handle division by zero, using a dictionary of small lambda functions.
- Mapping operators to functions
- Branching on the chosen operation
- Handling division by zero
"+"a + b"-"a - b"*"12 * 4 = 48"/"a / b, if b != 0The operator chooses the function
The problem
A calculator must choose the right operation for each symbol. A long chain of if / elif for every operator works, but it grows with every new operation and repeats the same structure.
Think of it like this
A dictionary of operations is like the keys of a pocket calculator. Each key (the operator symbol) is wired to one operation (a function). Pressing * runs multiplication on the two numbers directly, without asking a series of questions first.
"*": lambda left, right: left * right🔘 A key wired to its operationoperations[operator]👆 Press the * key(left, right)⚙️ Give it the two numbers12 * 4 = 48📟 The resultA dispatch table is a dictionary that maps keys, here operator symbols, to functions, so the program can look up and call the right function directly.
Key points
operationsmaps each symbol such as"+"to a smalllambdafunction.operations[operator]looks up the function for"*".operations[operator](left, right)calls that function with 12 and 4.- Adding a new operation means adding one line to the dictionary.
When should you use it?
- Choosing an action from user input: calculator operators, menu choices, game commands.
- Replacing long
if/elifchains that all do the same kind of thing. - Learning that functions can be stored in data structures.
When not to use it
- Only two cases: a plain
if/elseis easier to read. - Each case needs very different, multi-step logic: named functions or
matchstatements read better than lambdas.
Example code
operations = {
"+": lambda left, right: left + right,
"-": lambda left, right: left - right,
"*": lambda left, right: left * right,
"/": lambda left, right: left / right,
}
left, operator, right = 12, "*", 4
# Select and call the function associated with the operator.
print(f"{left} {operator} {right} = {operations[operator](left, right)}")
Result of running the code
12 * 4 = 48
Code explanation
operations is a dictionary whose values are functions written with lambda, one per operator symbol. left, operator, right = 12, "*", 4 sets up the calculation, and operations[operator] looks up the function stored under "*". Writing (left, right) right after the lookup calls that function, which returns 48.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.
Common mistakes
Not handling an unknown operator
operations["%"] raises KeyError.
print(operations[operator](left, right))
if operator in operations:
print(operations[operator](left, right))
else:
print("Unknown operator")
Dividing by zero
left / right fails with ZeroDivisionError when right is 0.
operations["/"](12, 0)
if operator == "/" and right == 0:
print("Cannot divide by zero")
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Average of Three Average three whole numbers. Easy
- Exact Fraction Arithmetic Perform fraction operations and return a reduced fraction. Medium