Book a free demo

Easy ยท ages 10+ ยท functions ยท parameters ยท dictionaries

A calculator with functions in Python.

Write functions for add, subtract, multiply and divide, and use a dictionary to choose one.

The program

Press Run to see what it prints. Change anything you like, then run it again.

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        return "Cannot divide by zero"
    return a / b

operations = {"+": add, "-": subtract, "*": multiply, "/": divide}

for a, op, b in [(8, "+", 5), (9, "-", 4), (6, "*", 7), (20, "/", 4), (5, "/", 0)]:
    print(a, op, b, "=", operations[op](a, b))
8 + 5 = 13
9 - 4 = 5
6 * 7 = 42
20 / 4 = 5.0
5 / 0 = Cannot divide by zero

How it works

  1. Each function takes two parameters and returns an answer. The divide function checks for zero first, because dividing by zero is an error.
  2. A dictionary pairs a key (the symbol) with a value (the function). operations[op] looks up the function, and the brackets after it call it.
  3. Functions are values in Python, so you can store them in dictionaries and lists.
See the Python path โ†’

Try this

  • Add a power operation with **.
  • Add a remainder operation with %.
  • Test your own pairs of numbers.

Stuck on an error? Read how to debug Python.

Similar ideas

More programs

All programs โ†’

FAQ

A calculator with functions: questions

What does the a calculator with functions program do?

Write functions for add, subtract, multiply and divide, and use a dictionary to choose one. It prints: 8 + 5 = 13 / 9 - 4 = 5 / 6 * 7 = 42 โ€ฆ

Which Python ideas does it use?

functions, parameters, dictionaries. Easy level, suitable from about age 10.

How do I run it?

Press Run on this page. To run it on your own computer, install Python 3 and save the code in a file ending in .py. It prints the same thing.

What should I try next?

Add a power operation with **. Add a remainder operation with %. Test your own pairs of numbers.

Start a conversation

Want a teacher to guide the learning?

Tell us the learner's age and what they can already do, and we will suggest a starting point. A parent or guardian can make the enquiry.

  • Tell us the learnerโ€™s age or grade and goals
  • Weโ€™ll suggest a suitable class or learning path
  • Weโ€™ll confirm format, timing and fees with a parent or guardian

For a childโ€™s class, please have a parent or guardian send the enquiry. Avoid sharing passwords or sensitive personal details.

Weโ€™ll use your details only to respond to this request.

Play it, don't just read it

Write some code right now

Free games that need no sign-up. Pick one and play for five minutes.

All free games โ†’
Chat on WhatsApp
Esc

Try