First Python Project: A Simple Calculator

Congratulations on getting started with Python! Let’s now build your first project: a Simple Calculator. This project will teach you how to interact with users, perform basic calculations, and organize your code into functions.


Project Overview

You will create a Python program that:

  • Prompts the user to input two numbers.
  • Asks the user to select an operation: addition, subtraction, multiplication, or division.
  • Displays the result of the selected operation.

Step 1: Plan Your Project

Info

Understanding the problem and planning your code is essential. Here’s what your calculator needs:

  1. A way to take input from the user.
  2. Logic to perform calculations based on the user’s choice.
  3. Clear and user-friendly output.

Step 2: Write the Code

Open your editor and create a new file named calculator.py. Add the following code:

# Simple Calculator in 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 "Error: Division by zero is not allowed."
    return a / b

print("Welcome to the Simple Calculator!")
print("Select an operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")

choice = input("Enter the number of your choice (1/2/3/4): ")

num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))

if choice == '1':
    print("The result is:", add(num1, num2))
elif choice == '2':
    print("The result is:", subtract(num1, num2))
elif choice == '3':
    print("The result is:", multiply(num1, num2))
elif choice == '4':
    print("The result is:", divide(num1, num2))
else:
    print("Invalid choice. Please run the program again.")

Step 3: Run the Program

  1. Save the file as calculator.py.
  2. Run the program:
    python calculator.py
    
  3. Follow the on-screen instructions to perform calculations.
Warning

Always validate user inputs to prevent errors like dividing by zero or entering invalid numbers.


How It Works

  1. Functions:
    Each mathematical operation (add, subtract, multiply, divide) is defined in a separate function for modularity.

  2. Input and Output:

    • The program takes input from the user using the input function.
    • It converts the input to float to handle decimal numbers.
  3. Decision Making:
    The program uses if-elif-else statements to perform the operation based on the user's choice.

Deep Dive

Why Use Functions?

Functions make your code reusable and easier to understand. You can extend this calculator by adding new functions for operations like modulus or power.

Copyright © 2025 Devship. All rights reserved.

Made by imParth