Login

Please fill in your details to login.





lesson 3.8.6 project: a modular calculator

Building a Calculator with a Function for Each Operation


image

Welcome to the Software House, Junior Developers! Today is the day you graduate from writing simple scripts to engineering real software tools. You've learned how to break problems down (decomposition), create reusable blocks (procedures), make them flexible (parameters), and get answers back (return values). Today, we combine all these skills to build a professional, modular Calculator App. This is exactly how professional Software Developers build complex operating systems and games - by building small, reliable modules and connecting them together. Get your IDEs ready; it's time to build!

Learning Outcomes
The Building Blocks (Factual Knowledge)
Recall the syntax for defining a function that accepts multiple parameters and returns a value.
Describe the difference between a local variable (inside a function) and a global variable (in the main program).
Identify the purpose of a 'main program loop' in keeping an application running.

The Connections and Theories (Conceptual Knowledge)
Analyse how 'Top-Down Design' allows us to code the structure of a program before writing the detailed logic.
Explain why separating the 'User Interface' (inputs/outputs) from the 'Logic' (calculations) makes code more robust and easier to test.
Evaluate the benefits of modular code when debugging specific errors (e.g., fixing the subtraction logic without breaking the addition logic).

The Skills and Methods (Procedural Outcomes)
Create a series of 'pure functions' that perform calculations and return results without printing.
Apply a 'while loop' to create a continuous menu-driven interface.
Construct a robust main program that coordinates calls to various helper functions based on user input.

Digital Skill Focus: The focus for this lesson is C.1.1 Software Proficiency. Students will utilize the debugging features of their IDE (Integrated Development Environment) to step through function calls, specifically observing how execution jumps from the main program to a function and back again.

Part 1: The Blueprint (Top-Down Design)


Before we write a single line of calculation logic, we need to set up the architecture of our program. In Lesson 3.8.2, we looked at Structure Charts. Today, we turn that chart into a code skeleton.

A professional program usually has two distinct parts:

1
The Logic Layer: These are your functions. They do the hard work (maths, processing) but they never talk to the user directly. They take inputs as parameters and send back answers as return values.
image
2
The Interface Layer: This is your main program. It handles the inputs (asking the user questions) and outputs (showing the result).

Before we start coding proper, we are going to use a special Python keyword called
pass
. This tells Python "I haven't written this code yet, but don't crash." It allows us to sketch out our functions before filling in the details.


time limit
Task 1 Laying the Foundations

It is time to be a Systems Architect! We need to define the structure of our calculator before we worry about the maths.

1
Create a New File

Open the Thonny IDE and make sure there is a new, blank script in the editor.
Organise your workspace.

2
Define the Structure

Copy the code below exactly by clicking the copy button. Notice the use of the
pass
keyword. This is a "ToDo" note for Python. It allows the code to run without errors even though the functions are empty.

# CALCULATOR PROJECT
# Author: [Student Name] # <-- Put your name here

# --- Logic Layer: FUNCTIONS ---
def add(a, b):
    pass

def subtract(a, b):
    pass

def multiply(a, b):
    pass

def divide(a, b):
    pass

# --- Interface Layer: MAIN PROGRAM ---
print("System Starting...")


3
Save and run your boilerplate script.

Press F5 or click the green play button.
You will be asked to save your script. Call it
modular_calc.py
After you click SAVE, your script will run and... do nothing.
This is correct - we have set up the boilerplate.

Outcome: You have a valid Python script with four defined (but empty) functions which does... nothing.

Checkpoint

Part 2: The Logic (Pure Functions)


Now we have our skeleton, we need to give it muscles. We are going to replace the
pass
keywords with actual logic.

Crucial Rule: These functions must NOT print anything.

If a function prints the answer, it is a "dead end" - the main program can't use that number for anything else. Instead, we use
return
. This hands the answer back to the main program, allowing us to store it, formatting it, or even use it in another calculation.

We call these Pure Functions because they don't have side effects (like printing to the screen); they just take data in and give data back.

time limit
Task 2 Coding the Logic

Now we need to make the functions actually work.

1
The Addition Function

Delete the word
pass
inside your
add
function and replace it with the return statement:

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


2
Complete the Set

Do the same for
subtract
,
multiply
, and
divide
. Ensure you use the correct symbols (
-
,
*
,
/
).

🤫 Solutions (don't peak)
def subtract(a, b):
    return a - b

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

def divide(a, b):
    return a / b


3
Test in the Shell

Run your program (Green Play Button). Nothing will happen! This is normal. The functions are defined, but we haven't called them yet. Type this into the shell/console to test them manually...

>>> add(5, 10)


...which should output
15
. Now, test your other functions in the same way. Make sure that you decide what the answer should be before you press ENTER.

Outcome: Four working pure functions that can be tested via the console.

Checkpoint

Part 3: The Controller (The Main Loop)


We have an engine (the functions), but we have no steering wheel! We need a way for the user to interact with our tool.

We will build a Main Loop. This is a
while True:
loop that keeps the program running forever (until the user chooses to quit). inside this loop, we need to:

1
Display a Menu.
2
Ask the user for their choice.
3
Ask for the two numbers.
4
Call the correct function.
5
Print the returned answer.

This is where the magic happens:
answer = add(num1, num2)
. We catch the returned value in a variable called
answer
and then we print it.


time limit
Task 3 The Main Event

Right! Let's build the interface. Add this code at the bottom of your script. (Remember - no indentation!).

1
The Infinite Loop

Start the engine:

while True:
    print("--- MENU ---")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")
    print("Press ENTER to quit")
    choice = input("Enter choice: ")


2
Handle the quit

We need to handle the quite before we start asking for numbers! Copy and paste this underneath.

    if choice == "":
        break


The
break
keyword forces the
while true:
loop to end and, since there are no instructions after it, the program finishes.

3
Get the Data

Now we are sure we don't want to quite, ask the user for the numbers once.

    number1 = float(input("Enter first number: "))
    number2 = float(input("Enter second number: "))


4
The Decision Logic

Now, use the functions you built earlier.

    if choice == "1":
        print("Result:", add(number1, number2))
    elif choice == "2":
        print("Result:", subtract(number1, number2))
    elif choice == "3":
        print("Result:", multiply(number1, number2))
    elif choice == "4":
        print("Result:", divide(number1, number2))


4
Run it and test it!!

That's it! We have a working (simple) calculator program. Press the F5 key to run your machine. Exhaustively test all four mathematical operations and the quit choice. Try some negative numbers, try some decimal numbers, try making num1 greater than num2 and then num1 less than num2.

Can you break it? Let's hope not!

Outcome: A fully functioning calculator that loops back to the start after every calculation.

Checkpoint

image
Today you have learnt how to engineer a modular software application by decomposing a complex problem into independent, pure functions and orchestrating them with a central main loop, just like a professional developer.

Out of Lesson Learning



Last modified: January 30th, 2026
The Computing Café works best in landscape mode.
Rotate your device.
Dismiss Warning