Python project 01
Python Simple Calculator Project
This beginner-friendly calculator is a small command-line program that accepts decimal values, performs addition, subtraction, multiplication, and division, and handles invalid input without abruptly stopping. It is an excellent first project for practising Python functions, loops, conditions, and error handling.
Start Python training in VizagView all project ideas
What you will build
At the end of this exercise, you will have a calculator that keeps running until the user chooses to quit. Rather than assuming every entry is correct, it calmly asks again when a number or operator is invalid. That small detail makes the project feel much more like a real application.
Skills practised
whileloops- Functions and return values
ifconditions- Exceptions and validation
Requirements
- Python 3.8 or later
- A terminal or command prompt
- No third-party packages
- About 20 minutes to build and test
Full Python code
Create a file named simple_calculator.py, copy the code below, and save it. The program uses Python’s built-in decimal module so calculations such as 12.5 + 3 remain clear and predictable for a beginner project.
from decimal import Decimal, InvalidOperation
def read_number(prompt):
"""Keep asking until the user enters a valid number."""
while True:
value = input(prompt).strip()
try:
return Decimal(value)
except InvalidOperation:
print("Please enter a valid number, for example 12, -3.5, or 0.25.")
def calculate(first, operator, second):
"""Return the result for one supported calculator operation."""
if operator == "+":
return first + second
if operator == "-":
return first - second
if operator == "*":
return first * second
if operator == "/":
if second == 0:
raise ZeroDivisionError("A number cannot be divided by zero.")
return first / second
raise ValueError("Unsupported operator")
def format_number(value):
"""Show Decimal values without unnecessary trailing zeroes."""
text = format(value, "f")
return text.rstrip("0").rstrip(".") if "." in text else text
def main():
print("Simple Python Calculator")
print("Choose +, -, *, or /. Type q to quit.\n")
while True:
operator = input("Operation: ").strip().lower()
if operator in {"q", "quit", "exit"}:
print("Calculator closed. Keep practising!")
break
if operator not in {"+", "-", "*", "/"}:
print("Choose one of these operators: +, -, *, /.\n")
continue
first = read_number("First number: ")
second = read_number("Second number: ")
try:
result = calculate(first, operator, second)
print(f"Result: {format_number(result)}\n")
except ZeroDivisionError as error:
print(f"{error}\n")
if __name__ == "__main__":
main()
How the calculator works
The main() function is the starting point. It repeatedly asks the user for an operator, then collects two numbers. Entering q, quit, or exit ends the loop cleanly.
The read_number() function has one job: turn a typed value into a number. If the user enters something like hello, Python raises an InvalidOperation error. We catch that error and ask for a valid number again. Keeping this logic in its own function makes the rest of the program easier to read.
The calculate() function performs the actual arithmetic. The division branch explicitly checks for zero before dividing. This gives the learner a useful, readable message instead of an unhandled error. Finally, format_number() removes unnecessary trailing decimal zeroes, so a result such as 15.500 is shown as 15.5.
Run the project
- Open a terminal in the folder where you saved the file.
- Run
python simple_calculator.py. On some Windows installations, usepy simple_calculator.py. - Enter an operator and two values. Try
+,-,*, and/. - Test an incorrect word and a division by zero. These checks help you see why validation matters.
Simple Python Calculator
Choose +, -, *, or /. Type q to quit.
Operation: /
First number: 12.5
Second number: 3
Result: 4.166666666666666666666666667
Operation: q
Calculator closed. Keep practising!
Notes for your notebook
- Validation: a program should guide the user after an invalid entry instead of failing silently.
- Division by zero: always check the denominator before division when users can enter the value.
- Functions: short functions with one clear responsibility are easier to test and reuse.
- Decimal values:
Decimalis useful when you want clear base-10 arithmetic. For many simple calculations, Python’sfloattype is also acceptable.
Ways to extend this project
Once the basic version works, add a calculation history, support for exponents and percentages, or a small graphical interface using Tkinter. Each upgrade gives you a reason to revisit the same core ideas while making the project more portfolio-ready. When you start building larger programs, the guide to Python functions will help you organise your code, and the introduction to classes and objects is a useful next step.
Where to go after the calculator
Once this calculator feels comfortable, build the Python To-Do List Application to practise working with changing data rather than only two values. Strengthen the code behind both projects with this guide to Python functions, then choose another challenge from the project ideas library. For guided assignments and feedback, visit the Python programming course in Vizag.