Site icon StudyGyaan

Simple Calculator Program in Python – Basic Mathematical Operations

Python Programming

In Python programming, a simple calculator program allows you to perform basic mathematical operations such as addition, subtraction, multiplication, and division. By implementing a calculator program, you can practice fundamental programming concepts and create a useful tool for performing calculations. In this blog post, we will explore how to build a simple calculator in Python, understand its structure, and provide examples to demonstrate its functionality.

Building a Simple Calculator Code

To create a simple calculator program in Python, we can define functions for each mathematical operation and provide a user-friendly interface for input and output. The program should handle invalid inputs and provide appropriate error messages.

Example: Python program for a simple calculator:

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 a / b
    else:
        raise ValueError("Error: Division by zero")

print("Simple Calculator Program")
print("Supported operations: +, -, *, /")

while True:
    num1 = float(input("Enter the first number: "))
    operator = input("Enter the operator (+, -, *, /): ")
    num2 = float(input("Enter the second number: "))

    if operator == "+":
        result = add(num1, num2)
    elif operator == "-":
        result = subtract(num1, num2)
    elif operator == "*":
        result = multiply(num1, num2)
    elif operator == "/":
        try:
            result = divide(num1, num2)
        except ValueError as error:
            print(error)
            continue
    else:
        print("Error: Invalid operator")
        continue

    print("Result:", result)

    choice = input("Do you want to perform another calculation? (y/n): ")
    if choice.lower() != "y":
        break

Conclusion

A simple calculator program in Python can be created by defining functions for basic mathematical operations and providing a user-friendly interface for input and output. In this blog post, we explored the structure of a simple calculator program and provided an example of its implementation. You can enhance the program by adding more operations or error handling mechanisms. Building a calculator program is an excellent way to practice programming concepts and create a useful tool for everyday calculations. Enjoy coding with your new calculator program!

Exit mobile version