Calculator Class

Tags: Class, Object

Write a Python program to create a class Calculator. Write methods add, subtract, multiply, and divide for basic arithmetic operations.

Example 1:

Input: calc = Calculator(), calc.add(5, 3), calc.subtract(10, 6), calc.multiply(7, 8), calc.divide(36, 6)

Output: 8, 4, 56, 6

Example 2:

Input: calc = Calculator(), calc.add(15, 25), calc.subtract(50, 20), calc.multiply(3, 5), calc.divide(45, 9)

Output: 40, 30, 15, 5

Define the class Calculator and then create the methods add, subtract, multiply, and divide to perform the basic arithmetic operations.

class Calculator:
    def add(self, a, b):
        return a + b

    def subtract(self, a, b):
        return a - b

    def multiply(self, a, b):
        return a * b

    def divide(self, a, b):
        if b != 0:
            return a / b
        else:
            return 'Error: Division by zero'

calc = Calculator()
print(calc.add(5, 3))  # Output: 8
print(calc.subtract(10, 6))  # Output: 4
print(calc.multiply(7, 8))  # Output: 56
print(calc.divide(36, 6))  # Output: 6

print(calc.add(15, 25))  # Output: 40
print(calc.subtract(50, 20))  # Output: 30
print(calc.multiply(3, 5))  # Output: 15
print(calc.divide(45, 9))  # Output: 5

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!