Basic Calculator in Python with Source Code

Basic Calculator in Python

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

Let’s get started!

Features

The Python calculator we’ll 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

Here’s an overview of what we’ll 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.

Let’s dive into the code!

https://updategadh.com/category/php-project

Step 1: Define Functions for Each Operation

The first thing we’ll 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.

See also  Secure Password Generator in Python With Source Code

Here’s 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, we’ve added basic error handling to avoid division by zero.

Step 2: Create the User Input System

Next, we’ll create a system that allows the user to input the numbers and choose the operation they want to perform. Python’s input() function will be used to collect user data.

Here’s 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 user’s input is valid and then prompts the user to input two numbers.
  • Based on the user’s selection, the corresponding function is called, and the result is displayed.
See also  Expense Tracker in Python with Source Code

Step 3: Add Error Handling and Final Touches

We’ve already added error handling for invalid numeric inputs and division by zero, but it’s important to ensure the user experience is smooth. Here’s a breakdown of what we added:

  • Handling non-numeric input: If the user enters something that isn’t 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.
Screenshot-2024-10-14-173315-1024x403 Basic Calculator in Python with Source Code
Basic Calculator in Python with Source Code
Screenshot-2024-10-14-173335-1024x401 Basic Calculator in Python with Source Code
Basic Calculator in Python with Source Code

Full Source Code for the Basic Calculator

Here’s 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

Post Comment