code Snippets

Basic Calculator in Python with Source Code

Basic Calculator in Python with Source Code

Basic Calculator in Python

If youre new to Python and looking for a fun and simple project to practice your programming skills, building a basic calculator is a perfect choice! Its a great way to learn core programming concepts like functions, loops, and user input. Plus, youll end up with a useful tool that can handle simple arithmetic operations like addition, subtraction, multiplication, and division.

Lets get started!

Features

The Python calculator well build will support the following operations:

  • Addition: Adding two numbers.
  • Subtraction: Subtracting one number from another.
  • Multiplication: Multiplying two numbers.
  • Division:Dividing an integer by another (with zero division mistake handled).

Download New Real Time Projects :-Click here

Steps to Build

Heres an overview of what well do:

  1. Construct a user input mechanism to gather operators and numbers.
  2. For every arithmetic operation, create a function.
  3. Implement a menu system to guide the user through the operations.
  4. Add error handling to make sure the calculator works smoothly.

Lets dive into the code!

Step 1: Define Functions for Each Operation

The first thing well do is define separate functions for each of the basic arithmetic operations (addition, subtraction, multiplication, and division). This will make the code more modular and easier to understand.

Heres the code to define the basic operations:

# Function for addition
def add(x, y):
    return x + y

# Function for subtraction
def subtract(x, y):
    return x - y

# Function for multiplication
def multiply(x, y):
    return x * y

# Function for division
def divide(x, y):
    if y == 0:
        return "Error! Division by zero is not allowed."
    else:
        return x / y

Explanation:

  • We define four separate functions, each taking two parameters (x and y), which represent the two numbers that the user will input.
  • For the division function, weve added basic error handling to avoid division by zero.

Step 2: Create the User Input System

Next, well create a system that allows the user to input the numbers and choose the operation they want to perform. Pythons input() function will be used to collect user data.

Heres the code for gathering user input and choosing an operation:

def calculator():
    print("Welcome to the Basic Python Calculator!")

    # Display the available operations
    print("Select operation:")
    print("1. Addition")
    print("2. Subtraction")
    print("3. Multiplication")
    print("4. Division")

    # Take input from the user
    choice = input("Enter choice (1/2/3/4): ")

    if choice in ['1', '2', '3', '4']:
        # Input the numbers
        try:
            num1 = float(input("Enter first number: "))
            num2 = float(input("Enter second number: "))
        except ValueError:
            print("Invalid input! Please enter numeric values.")
            return

        # Perform the chosen operation
        if choice == '1':
            print(f"{num1} + {num2} = {add(num1, num2)}")
        elif choice == '2':
            print(f"{num1} - {num2} = {subtract(num1, num2)}")
        elif choice == '3':
            print(f"{num1} * {num2} = {multiply(num1, num2)}")
        elif choice == '4':
            print(f"{num1} / {num2} = {divide(num1, num2)}")
    else:
        print("Invalid choice! Please select a valid operation.")

# Call the calculator function to run the program
calculator()

Explanation:

  • The program first displays a menu of available operations (Addition, Subtraction, Multiplication, and Division).
  • It then asks the user to select an operation by entering 1, 2, 3, or 4.
  • The program checks whether the users input is valid and then prompts the user to input two numbers.
  • Based on the users selection, the corresponding function is called, and the result is displayed.

Step 3: Add Error Handling and Final Touches

Weve already added error handling for invalid numeric inputs and division by zero, but its important to ensure the user experience is smooth. Heres a breakdown of what we added:

  • Handling non-numeric input: If the user enters something that isnt a number, the program will print an error message and exit gracefully.
  • Handling invalid choices: If the user selects an option outside of the given choices (1, 2, 3, 4), the program will inform them and stop.
  • Handling division by zero: We added an extra check to avoid dividing by zero, which is a common error in calculators.

Full Source Code for the Basic Calculator

Heres the full code for the Basic Python Calculator:

# Basic Calculator in Python

# Function for addition
def add(x, y):
    return x + y

# Function for subtraction
def subtract(x, y):
    return x - y

# Function for multiplication
def multiply(x, y):
    return x * y

# Function for division with error handling for division by zero
def divide(x, y):
    if y == 0:
        return "Error! Division by zero is not allowed."
    else:
        return x / y

# Main calculator function
def calculator():
    print("Welcome to the Basic Python Calculator!")

    # Display the available operations
    print("Select operation:")
    print("1. Addition")
    print("2. Subtraction")
    print("3. Multiplication")
    print("4. Division")

    # Take input from the user
    choice = input("Enter choice (1/2/3/4): ")

    if choice in ['1', '2', '3', '4']:
        # Input the numbers
        try:
            num1 = float(input("Enter first number: "))
            num2 = float(input("Enter second number: "))
        except ValueError:
            print("Invalid input! Please enter numeric values.")
            return

        # Perform the chosen operation
        if choice == '1':
            print(f"{num1} + {num2} = {add(num1, num2)}")
        elif choice == '2':
            print(f"{num1} - {num2} = {subtract(num1, num2)}")
        elif choice == '3':
            print(f"{num1} * {num2} = {multiply(num1, num2)}")
        elif choice == '4':
            print(f"{num1} / {num2} = {divide(num1, num2)}")
    else:
        print("Invalid choice! Please select a valid operation.")

# Call the calculator function to run the program
calculator()

How to Run the Calculator Program

  1. Copy the above code and paste it into a Python file (e.g., calculator.py).
  2. Open your terminal or command prompt.
  3. Go to the directory containing your Python file.
  4. Run the script by typing python calculator.py.

You can now perform basic arithmetic operations directly from your terminal!

  • Basic Calculator in Python with Source Code
  • Basic Calculator in Python
Source Code Available

Interested in This Project?

Get the complete source code for this project at a very affordable price — perfect for your portfolio, college submission, or learning. Message us on WhatsApp and we'll get back to you instantly!

Full source code included Step-by-step setup guide Instant delivery on WhatsApp Instant reply on WhatsApp
Chat on WhatsApp

We usually reply within a few minutes

Leave a Reply

Your email address will not be published. Required fields are marked *

Chat with us