program for calculator in python with source code

Program for calculator in python with source code



program for calculator in python with source code



This program for calculator in Python is designed to perform basic simple calculator arithmetic operations like addition, subtraction, multiplication, and division. Below is an explanation of the code structure and functionality in detail:


Addition Function: This function takes two parameters, x and y, and returns their sum. This function is used when the user selects the addition operation.


Subtraction Function: Similarly, this function subtracts the second number (y) from the first (x) and returns the result.


Multiplication Function: This multiplies the two numbers provided as input and returns the product.


Division Function: This performs division between two numbers. It checks if the second number (y) is zero and returns an error message to avoid division by zero, which is mathematically undefined.


Read Also:-


Main Function: calculator()



# Function to add two numbers
def add(x, y):
    return x + y


# Function to subtract two numbers
def subtract(x, y):
    return x - y


# Function to multiply two numbers
def multiply(x, y):
    return x * y


# Function to divide two numbers
def divide(x, y):
    if y == 0:
        return "Error! Division by zero."
    else:
        return x / y


# Function to handle user input and perform calculations
def calculator():
    while True:
        print("\nSelect operation:")
        print("1. Add")
        print("2. Subtract")
        print("3. Multiply")
        print("4. Divide")
        print("5. Exit")

        choice = input("Enter choice (1/2/3/4/5): ")

        # Exit the program
        if choice == '5':
            print("Exiting the calculator. Goodbye!")
            break

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

            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':
                result = divide(num1, num2)
                print(f"{num1} / {num2} = {result}")
        else:
            print("Invalid choice! Please select a valid option.")


# Run the calculator program
calculator()
  
  

User Interface: The program displays a menu with five options: Add, Subtract, Multiply, Divide, and Exit. The user can select the operation by entering a corresponding number (1-5).

Choice Handling: The program captures the user’s input and checks whether it matches a valid option. If the user chooses 5, the program will exit, printing a farewell message

Input Validation: When a valid operation is selected, the program prompts the user to enter two numbers. The input is converted to floating-point numbers (float) to allow for decimal calculations. If the input is not a valid number (e.g., text), the program catches the error with a try-except block and asks the user to re-enter the values.

Performing the Operation: Depending on the user’s choice (1, 2, 3, or 4), the program calls the corresponding function (addition, subtraction, multiplication, or division) and prints the result of the operation.

Invalid Choice Handling: If the user enters an invalid option, the program prints an error message and prompts the user to try again.


Output:




Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter choice (1/2/3/4/5): 1
Enter first number: 20
Enter second number: 20
20.0 + 20.0 = 40.0

Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
5. Exit
Enter choice (1/2/3/4/5): 4
Enter first number: 35
Enter second number: 5
35.0 / 5.0 = 7.0


Key Features of this Python Calculator:

Looping for Multiple Operations: The program continuously prompts the user for operations until they choose to exit, making it useful for performing multiple calculations in one session.

Error Handling: The calculator handles invalid inputs gracefully, ensuring that non-numeric inputs don’t crash the program.

Division by Zero Prevention: The division function checks for zero in the denominator to prevent runtime errors.

Conclusion:


This program for calculator in Python is a simple and interactive tool that allows users to perform arithmetic operations efficiently. It includes user-friendly features such as input validation, error handling, and a continuous operation loop, making it an ideal basic calculator implemented in Python.
Previous Post Next Post