Python Simple Calculator Script

Build a basic calculator in Python. Learn how to map mathematical operators, take user execution flows, and handle logic natively.

Try Python Simple Calculator Script Code

How it Works

A simple calculator program is an excellent entry point to utilizing Python functions, logic statements, and numerical types.

This script abstracts the basic operations (+, -, *, /) into standalone functions, creating a clean logical map.

You can further expand this to accept `input()` parameters from users in an interactive console context.

Source Code

Executing standard mathematical procedures via scoped functions wrapped in a dictionary mapping framework.

calculator.py
Try in Editor
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

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

num1, num2 = 12, 4

print("Calculator Demo")
for op_symbol, func in operations.items():
    print(f"{num1} {op_symbol} {num2} = {func(num1, num2)}")
Terminal Output
Calculator Demo
12 + 4 = 16
12 - 4 = 8
12 * 4 = 48
12 / 4 = 3.0

Real-world Applications

  • Creating embedded CLI utility tools
  • Practicing dictionary-based switch-case emulation
  • Fundamental arithmetic modeling for custom math engines

Frequently Asked Questions

Why use a dictionary for operations?

Mapping string symbols (like "+") to functions prevents writing long, repetitive if/elif chains. It is a highly "Pythonic" approach.

More Examples