Simple Calculator in Python
A calculator combines branching, operators, and reusable functions.
What is Simple Calculator?
A calculator combines branching, operators, and reusable functions.
Apply a selected arithmetic operation.
When should you use it?
- Learn Python syntax through a practical example.
- Build a foundation for larger programming problems.
- Test an idea quickly without a local setup.
Example code
main.py
operations = {
"+": lambda left, right: left + right,
"-": lambda left, right: left - right,
"*": lambda left, right: left * right,
"/": lambda left, right: left / right,
}
left, operator, right = 12, "*", 4
# Select and call the function associated with the operator.
print(f"{left} {operator} {right} = {operations[operator](left, right)}")
Expected output
12 * 4 = 48
How it works
A dictionary maps each supported operator to its calculation.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.