Skip to Content
Course content

82: Practice Exercise: Building a Calculator with Functions

Click on the "Edit" button in the top corner of the screen to edit your slide content.

You've learned how to write functions, but the real magic happens when you stop thinking about them as isolated snippets of code and start thinking about them as building blocks for a tool. To get a feel for this, we're going to build a basic calculator. It sounds simple, but it's the perfect way to practice delegating logic to specific functions so your main program doesn't become a tangled mess.

Defining the core math operations

I always start by writing the "engine" before the "dashboard." In this case, the engine is just a set of functions that do one thing and do it well. I'm going to define four basic functions. Notice how I'm keeping these lean—no input prompts inside these functions, just raw calculations. This makes them reusable elsewhere if we ever decided to turn this into a GUI app or a web service.

def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

def multiply(x, y):
    return x * y

def divide(x, y):
    if y == 0:
        return "Error: Division by zero!"
    return x / y

Connecting user input to the logic

Now we need a way to let the user decide which operation to run. I could use a massive if/elif block inside a main function, which is exactly what I'll do here. I like to keep the "orchestration" logic separate from the "calculation" logic. It keeps the code readable.

def calculator():
    print("Select operation: +, -, *, /")
    choice = input("Enter choice: ")

    num1 = input("Enter first number: ")
    num2 = input("Enter second number: ")

    if choice == '+':
        print("Result:", add(num1, num2))
    elif choice == '-':
        print("Result:", subtract(num1, num2))
    elif choice == '*':
        print("Result:", multiply(num1, num2))
    elif choice == '/':
        print("Result:", divide(num1, num2))
    else:
        print("Invalid input")

The "string concatenation" trap

I just ran the code above and realized I made a classic mistake. If I enter 10 and 5 and choose addition, the program prints 105 instead of 15. Why? Because input() always returns a string. Python is doing string concatenation instead of mathematical addition.

I need to cast those inputs to floats before passing them into my functions. I'll fix this by wrapping the input() calls. I'm using float() instead of int() because a calculator that can't handle decimals isn't much of a calculator.

# Fixed version of the input section
    num1 = float(input("Enter first number: "))
    num2 = float(input("Enter second number: "))

Adding a loop for a better experience

Right now, the program runs once and then dies. That's annoying for the user. I'll wrap the whole thing in a while loop and add a "quit" option. This transforms it from a script into a legitimate little application.

def calculator():
    while True:
        print("\nSelect operation: +, -, *, / (or 'q' to quit)")
        choice = input("Enter choice: ")

        if choice.lower() == 'q':
            print("Closing calculator. Goodbye!")
            break

        if choice in ('+', '-', '*', '/'):
            try:
                num1 = float(input("Enter first number: "))
                num2 = float(input("Enter second number: "))
                
                if choice == '+':
                    print("Result:", add(num1, num2))
                elif choice == '-':
                    print("Result:", subtract(num1, num2))
                elif choice == '*':
                    print("Result:", multiply(num1, num2))
                elif choice == '/':
                    print("Result:", divide(num1, num2))
            except ValueError:
                print("Invalid input! Please enter numeric values.")
        else:
            print("Invalid operator selected.")

calculator()

I added a try/except block there because users love to type "banana" when you ask for a number. This prevents the whole program from crashing just because of one typo.




📋 Practical Task

Exercise: Adding an Exponent Function to the Calculator

Your task is to extend the calculator we just built. Currently, it only handles the four basic operations. I want you to add the ability to calculate exponents (raising one number to the power of another).

  • Create a new function called power(x, y) that returns x raised to the power of y.
  • Update the calculator() function's menu to include the ** operator.
  • Update the if/elif logic to call your new power function when ** is selected.
  • Test it by calculating 2 to the power of 3 (which should return 8.0).
Rating
0 0

There are no comments for now.

to be the first to leave a comment.