Beginner Python Exercises

Simple Calculator in Python

Pick an operator, apply it to two numbers and handle division by zero, using a dictionary of small lambda functions.

  • Beginner
  • 2 min read
  • 1 runnable example
What you'll learn
  • Mapping operators to functions
  • Branching on the chosen operation
  • Handling division by zero
calculate(12, "*", 4)
"+"a + b
"-"a - b
"*"12 * 4 = 48
"/"a / b, if b != 0

The 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.

From calculator keys to code
"*": lambda left, right: left * right🔘 A key wired to its operation
operations[operator]👆 Press the * key
(left, right)⚙️ Give it the two numbers
12 * 4 = 48📟 The result
Look up the function by its symbol, then call it.
In one sentence

A 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

  1. operations maps each symbol such as "+" to a small lambda function.
  2. operations[operator] looks up the function for "*".
  3. operations[operator](left, right) calls that function with 12 and 4.
  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 / elif chains 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 / else is easier to read.
  • Each case needs very different, multi-step logic: named functions or match statements read better than lambdas.

Example code

Run code →
main.py
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)}")
Get a Run button for this example

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.

  1. Change the input and predict the output before running.
  2. Handle empty or invalid input.
  3. Wrap the logic in a function and add more test cases.
Run in the Python compiler →

Common mistakes

Not handling an unknown operator

operations["%"] raises KeyError.

Problem
print(operations[operator](left, right))
Fix
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.

Problem
operations["/"](12, 0)
Fix
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.

All challenges