Python code for a calculator

In this code, we will be writing code for a calculator that does addition, subtraction, multiplication, and division. We have also included unit tests for these functions.

def add(a, b):
    """
    This function adds two numbers and returns the result
    """
    return a + b

def subtract(a, b):
    """
    This function subtracts two numbers and returns the result
    """
    return a - b

def multiply(a, b):
    """
    This function multiplies two numbers and returns the result
    """
    return a * b

def divide(a, b):
    """
    This function divides two numbers and returns the result
    """
    return a / b

# Unit tests
assert add(2, 3) == 5, "Test Case 1 Failed"
assert subtract(5, 2) == 3, "Test Case 2 Failed"
assert multiply(2, 3) == 6, "Test Case 3 Failed"
assert divide(6, 3) == 2, "Test Case 4 Failed"

print("All test cases passed!")

Explanation:

  • The first four functions (add, subtract, multiply, divide) implement the basic arithmetic operations of addition, subtraction, multiplication, and division.
  • The assertions at the end of the code are unit tests. They check that the output of each function is correct for given inputs.
  • If all the tests pass, the message “All test cases passed!” is printed. If any of the tests fail, an error message indicating which test case failed is printed.