Python Simple Calculator Script
Build a basic calculator in Python. Learn how to map mathematical operators, take user execution flows, and handle logic natively.
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.
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)}")Calculator Demo
12 + 4 = 16
12 - 4 = 8
12 * 4 = 48
12 / 4 = 3.0Real-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
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.