Python
Python

 

Introduction

A simple calculator is a basic program that can perform the four fundamental arithmetic operations: addition, subtraction, multiplication, and division. The purpose of this program is to give users the ability to perform basic mathematical operations through a user-friendly interface. The calculator accepts two numbers and allows the user to choose the operation they wish to perform.

Objective

The objective of this Python program is to:

  • Allow users to input two numbers.
  • Let the user select one of the four basic arithmetic operations: addition, subtraction, multiplication, or division.
  • Display the result of the operation chosen by the user.

Python Code for Simple Calculator


# Simple Calculator in Python

# 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

# Main program
def calculator():
    print("Select operation:")
    print("1. Add")
    print("2. Subtract")
    print("3. Multiply")
    print("4. Divide")

    # Taking user input
    choice = input("Enter choice (1/2/3/4): ")

    # Ensure the choice is valid
    if choice not in ['1', '2', '3', '4']:
        print("Invalid input. Please select a valid operation.")
        return

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

    if choice == '1':
        print(f"The result of {num1} + {num2} is: {add(num1, num2)}")
    elif choice == '2':
        print(f"The result of {num1} - {num2} is: {subtract(num1, num2)}")
    elif choice == '3':
        print(f"The result of {num1} * {num2} is: {multiply(num1, num2)}")
    elif choice == '4':
        print(f"The result of {num1} / {num2} is: {divide(num1, num2)}")

# Running the calculator program
if __name__ == "__main__":
    calculator()
        

Explanation of the Program Structure

The program consists of the following parts:

  1. Functions for Arithmetic Operations: The program defines four functions: add(), subtract(), multiply(), and divide(). Each of these functions takes two arguments (numbers) and performs the corresponding mathematical operation.
  2. Input Validation: In the main part of the program, the user is asked to select an operation (addition, subtraction, multiplication, or division). The program checks if the input is valid. If not, it asks the user to input a valid choice.
  3. Performing the Operation: Once the user selects an operation and enters two numbers, the program calls the corresponding function to perform the calculation. It then prints the result of the operation.
  4. Error Handling for Division: If the user chooses division and the second number is zero, the divide() function returns an error message (“Error! Division by zero.”) to prevent a runtime error.

How to Run the Program

  1. Install Python on your computer (if not already installed). You can download it from here.
  2. Open a text editor (like Notepad on Windows or any code editor like Visual Studio Code, Sublime Text, etc.) and paste the Python code into a new file.
  3. Save the file with a .py extension, for example calculator.py.
  4. Open a terminal or command prompt.
  5. Navigate to the directory where the calculator.py file is saved.
  6. Type python calculator.py and press Enter.
  7. The program will ask you to choose an operation and input two numbers. It will then display the result of the selected operation.

Example Output


Select operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter choice (1/2/3/4): 1
Enter first number: 5
Enter second number: 3
The result of 5.0 + 3.0 is: 8.0
        

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)