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
- Each function takes two parameters and returns an answer. The
dividefunction checks for zero first, because dividing by zero is an error. - 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. - Functions are values in Python, so you can store them in dictionaries and lists.
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
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
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.
Pick a game
- Predict the OutputRead a short Python program and choose what it prints. Then watch it runโฆPlay
- Bug HunterA Python program prints the wrong answer. Find the one line with theโฆPlay
- Code BuilderThe lines of a Python program are mixed up. Tap them into the rightโฆPlay
- Code JungleWrite real Python to guide Miko the monkey to every banana. 24 levels:โฆPlay