Implement a simple calculator class in Python

Document 对象参考手册Python3 Examples

We will use Python to implement a simple calculator class, which will contain basic addition, subtraction, multiplication, and division methods.

Example

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:
            raise ValueError("Cannot divide by zero!")
        return a / b

# Example usage
calc = Calculator()
print("Addition: ", calc.add(10, 5))
print("Subtraction: ", calc.subtract(10, 5))
print("Multiplication: ", calc.multiply(10, 5))
print("Division: ", calc.divide(10, 5))

Code explanation:

  • CalculatorThe class defines four methods:add, subtract, multiply, anddivide。
  • addmethod takes two parametersaandb, and returns their sum.
  • subtractmethod takes two parametersaandb, and returns their difference.
  • multiplymethod takes two parametersaandb, and returns their product.
  • dividemethod takes two parametersaandb, and returns their quotient. Ifbis 0, it raises aValueErrorexception, because the divisor cannot be zero.

Output result:

Addition:  15
Subtraction:  5
Multiplication:  50
Division:  2.0

This simple calculator class can perform basic mathematical operations, and through exception handling ensures the safety of division.

Document 对象参考手册Python3 Examples

Other extensions