Simple Python Calculator Code: Full Tutorial & Guide
This Snippet is coded by a user inOnline python Compiler. You can see and run this code too.
زبان: python
This snippet implements a command-line calculator in Python with an interactive menu covering the four basic arithmetic operations.
What the code does
- Menu display: Prints options for addition (+), subtraction (-), multiplication (*), division (/) and exit.
- Infinite loop:
while Truekeeps the calculator running until the user selects option 5, then exits viabreak. - Input validation: Any choice outside
['1','2','3','4']triggers an error message andcontinuerestarts the loop. - Numeric input:
float(input(...))accepts both integers and decimals. - Error handling: A
try/except ValueErrorblock prevents a crash when the user types letters instead of numbers. - Division-by-zero guard: The divisor is checked before the operation to avoid
ZeroDivisionError. - Formatted output: Results are printed with f-strings using readable symbols like × and ÷.
How to use it
- Save the code as
calculator.py. - Run
python calculator.pyin your terminal. - Pick an operation number, then enter two numbers.
Important note about the provided snippet
The pasted code has missing indentation inside def calculator(): and the final line print("\\n" + "="*30 + "\\n" lacks a closing parenthesis, so it will raise a SyntaxError as-is. Also add if __name__ == "__main__": calculator() so the function actually runs.
Possible extensions
- Add power, square root and percentage operations
- Switch to
match/case(Python 3.10+) for cleaner branching - Log calculation history to a CSV file
- Build a GUI version with Tkinter