← Back to Python Projects

Python Calculator

About This Project

This Python Calculator is a beginner-friendly project that demonstrates how to build a functional calculator using Python. It supports basic arithmetic operations and provides a simple command-line interface for users.

Features

  • Basic arithmetic operations: Addition, Subtraction, Multiplication, Division
  • Clear function to reset calculator
  • Error handling for invalid inputs
  • Looping menu for multiple calculations
  • Easy to understand and modify code

Source Code

# Python Calculator
# A simple calculator using Python

def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b != 0:
        return a / b
    else:
        return "Error: Division by zero"

def calculator():
    print("Welcome to Python Calculator!")
    print("Select operation:")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")
    
    while True:
        choice = input("Enter choice (1/2/3/4): ")
        
        if choice in ['1', '2', '3', '4']:
            num1 = float(input("Enter first number: "))
            num2 = float(input("Enter second number: "))
            
            if choice == '1':
                print(f"Result: {num1} + {num2} = {add(num1, num2)}")
            elif choice == '2':
                print(f"Result: {num1} - {num2} = {subtract(num1, num2)}")
            elif choice == '3':
                print(f"Result: {num1} * {num2} = {multiply(num1, num2)}")
            elif choice == '4':
                print(f"Result: {num1} / {num2} = {divide(num1, num2)}")
        else:
            print("Invalid Input")
        
        next_calculation = input("Let's do next calculation? (yes/no): ")
        if next_calculation.lower() != 'yes':
            break

if __name__ == "__main__":
    calculator()

How It Works

  1. The program displays a menu with four operation choices
  2. User selects an operation by entering a number (1-4)
  3. User enters two numbers for the calculation
  4. The program performs the selected operation using functions
  5. Result is displayed to the user
  6. User can choose to perform another calculation or exit

Concepts Used

Functions
While Loops
Conditionals
User Input