Write a program of calculator in python - Calculator program in python - Python Programs

 Calculator Program in Python

Here's a Python program for a simple calculator that can perform basic arithmetic operations:

Python Code:

def calculator(num1, num2, operator):

    """

    Performs the given arithmetic operation on the two numbers.

    """

    if operator == '+':

        return num1 + num2

    elif operator == '-':

        return num1 - num2

    elif operator == '*':

        return num1 * num2

    elif operator == '/':

        if num2 == 0:

            raise ValueError("Cannot divide by zero")

        return num1 / num2

    else:

        raise ValueError("Invalid operator")


Here is the Practical of the above program in Jupyter Notebook



# Example usage

print(calculator(4, 2, '+'))  # 6

print(calculator(4, 2, '-'))  # 2

print(calculator(4, 2, '*'))  # 8

print(calculator(4, 2, '/'))  # 2.0


The calculator function takes two numbers (num1 and num2) and an operator (+, -, *, or /) as input, and performs the arithmetic operation on the two numbers using the given operator. If the operator is not one of the four supported operations, the function raises a ValueError. If the operator is division (/), the function checks for a division by zero and raises a ValueError if the second number is 0.

Note that this is a simple example of a calculator program, and it does not handle more complex expressions or input validation (such as checking if the inputs are valid numbers). If you want to build a more advanced calculator, you may need to use a parsing library or implement a more sophisticated algorithm.

Comments