Python Coding Day 20 | Building a Smart Calculator in Python: A Step-by-Step Guide

Building a Smart Calculator in Python: A Step-by-Step Guide

Watch the lesson tutorial  ðŸ”»


Today, we are going to build a fully functional Calculator using Python. This isn't just a simple script; it uses functions, dictionaries, and recursion to allow users to chain calculations together (e.g., taking the result of one math problem and using it immediately in the next).

This tutorial is optimized for Google Colab, so you can copy the code and run it directly in your browser.

1. Setting the Scene: Imports and UI

First, we need to handle the visuals. Since we aren't using an external file for the logo or the replit library for clearing the screen, we will import a tool for Google Colab and define our logo manually.

The Code

# Import clear_output for Google Colab environments
from IPython.display import clear_output

# Creating the logo variable directly in the code
logo = """
 _____________________
|  _________________  |
| |              0. | |
| |_________________| |
|  ___ ___ ___   ___  |
| | 7 | 8 | 9 | | + | |
| |___|___|___| |___| |
| | 4 | 5 | 6 | | - | |
| |___|___|___| |___| |
| | 1 | 2 | 3 | | x | |
| |___|___|___| |___| |
| | . | 0 | = | | / | |
| |___|___|___| |___| |
|_____________________|
"""

Explanation

  1. from IPython.display import clear_output: In standard Python, we might use os.system('cls'). However, because we are running this in a Notebook (Colab), we use this specific import to clear the screen nicely when the user starts a new calculation.

  2. logo = """ ... """: We use triple quotes to create a multi-line string. This stores our ASCII art in a variable so we can print it whenever the calculator starts.

2. Defining the Logic: Mathematical Functions

Next, we define the core behaviors. We need four separate functions to handle the basic arithmetic.

The Code

def add(n1, n2):
  return n1 + n2

def subtract(n1, n2):
  return n1 - n2

def multiply(n1, n2):
  return n1 * n2

def divide(n1, n2):
  return n1 / n2

Explanation

  • def function_name(n1, n2):: We define functions that accept two inputs (arguments), n1 and n2.

  • return: These functions don't just print the answer; they send the data back. This allows us to store the result in a variable later.

3. The Brains: Mapping Symbols to Functions

This is the most "Pythonic" part of the script. Instead of writing a long if/elif statement (e.g., if symbol == "+": do this), we store the functions inside a Dictionary.

The Code

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

Explanation

  • Keys (+, -, etc.): These are strings that the user will type.

  • Values (add, subtract): Notice there are no parentheses () after the function names. We are storing the name of the function, not calling it yet.

  • Why do this?: It allows us to pick a function dynamically based on user input.

4. The Engine: The calculator() Function

Now we combine everything into a recursive function. This means the function can call itself to restart the program.

The Code

def calculator():
  # 1. Show the logo
  print(logo)

  # 2. Get the first number
  num1 = float(input("What's the first number?: "))

  # 3. Show available symbols
  for symbol in operations:
    print(symbol)
  
  should_continue = True
 
  while should_continue:
    # 4. Get operation and second number
    operation_symbol = input("Pick an operation: ")
    num2 = float(input("What's the next number?: "))
    
    # 5. Retrieve the function from the dictionary
    calculation_function = operations[operation_symbol]
    
    # 6. Call the retrieved function
    answer = calculation_function(num1, num2)

    # 7. Display result
    print(f"{num1} {operation_symbol} {num2} = {answer}")

    # 8. Check if user wants to chain calculation or restart
    if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ") == 'y':
      num1 = answer
    else:
      should_continue = False
      clear_output() # Clears the Colab screen
      calculator()   # Recursion: The function calls itself

Explanation of Key Lines

  1. for symbol in operations:: Loops through the dictionary keys and prints +, -, *, / so the user knows what to type.

  2. calculation_function = operations[operation_symbol]:

    • If the user typed *, this looks inside the dictionary, finds the key *, and grabs the value multiply.

    • calculation_function becomes the multiply function.

  3. answer = calculation_function(num1, num2): This actually runs the math.

  4. num1 = answer: If the user types 'y', we update num1 to be the previous answer. The loop runs again, but now uses the new total as the starting point.

  5. calculator(): If the user types 'n', we stop the while loop, clear the screen, and call calculator() again to start fresh.

5. Complete Runnable Code

Here is the full script combined. You can copy this block directly into a Google Colab cell and run it.

from IPython.display import clear_output

# ASCII Logo
logo = """
 _____________________
|  _________________  |
| |              0. | |
| |_________________| |
|  ___ ___ ___   ___  |
| | 7 | 8 | 9 | | + | |
| |___|___|___| |___| |
| | 4 | 5 | 6 | | - | |
| |___|___|___| |___| |
| | 1 | 2 | 3 | | x | |
| |___|___|___| |___| |
| | . | 0 | = | | / | |
| |___|___|___| |___| |
|_____________________|
"""

# Arithmetic Functions
def add(n1, n2):
  return n1 + n2

def subtract(n1, n2):
  return n1 - n2

def multiply(n1, n2):
  return n1 * n2

def divide(n1, n2):
  return n1 / n2

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

# Recursive Calculator Function
def calculator():
  print(logo)

  # Error handling added for robust input
  try:
      num1 = float(input("What's the first number?: "))
  except ValueError:
      print("Invalid number.")
      return calculator()

  for symbol in operations:
    print(symbol)
  
  should_continue = True
 
  while should_continue:
    operation_symbol = input("Pick an operation: ")
    
    # Check if operation exists
    if operation_symbol not in operations:
        print("Invalid operation chosen. Please start over.")
        continue

    try:
        num2 = float(input("What's the next number?: "))
    except ValueError:
        print("Invalid number.")
        continue

    calculation_function = operations[operation_symbol]
    answer = calculation_function(num1, num2)
    print(f"{num1} {operation_symbol} {num2} = {answer}")

    if input(f"Type 'y' to continue calculating with {answer}, or type 'n' to start a new calculation: ") == 'y':
      num1 = answer
    else:
      should_continue = False
      clear_output()
      calculator()

# Start the program
calculator()

- by Chirana Nimnaka

Comments

Popular posts from this blog

Python Coding Day 1 | The print() Function and Comments

What is Python?

Set Up an Environment to Code in Python