In this exercise, you have to implement a calculator that can perform addition, subtraction, multiplication, and division.
Problem statement
Write a Python class called Calculator by completing the tasks below:
Task 1
Initializer:
Implement an initializer to initialize the values of num1 and num2
Properties:
num1
num2
Task 2
Methods:
add() is a method that returns the sum of num1 and num2.
subtract() is a method that returns the subtraction of num1 from num2.
multiply() is a method that returns the product of num1 and num2.
divide() is a method that returns the division of num2 by num1.
Input:
Pass numbers (integers or floats) in the initializer.
Output:
addition, subtraction, division, and multiplication
Sample input:
1 2 3 4 5 | obj = Calculator(10, 94); obj.add() obj.subtract() obj.multiply() obj.divide() |
Sample method output:
1 2 3 4 | 104 84 940 9.4 |
Coding exercise
Design a step-by-step algorithm before jumping to the implementation.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | class Calculator: def __init__(self): pass def add(self): pass def subtract(self): pass def multiply(self): pass def divide(self): pass |
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class Calculator: def __init__(self, num1, num2): self.num1 = num1 self.num2 = num2 def add(self): return (self.num2 + self.num1) def subtract(self): return (self.num2 - self.num1) def multiply(self): return (self.num2 * self.num1) def divide(self): return (self.num2 / self.num1) demo1 = Calculator(10, 94) print("Addition:", demo1.add()) print("Subtraction:", demo1.subtract()) print("Mutliplication:", demo1.multiply()) print("Division:", demo1.divide()) |
Explanation
We have implemented the Calculator class, which has the two properties, num1 and num2.
In the initializer, at line 3 – 4, we have initialized both properties, num1 and num2.
In line 7, we implemented add(), a method that returns the sum, num1 + num2, of both properties.
In line 10, we implemented subtract(), a method that returns the subtraction of num1 from num2.
In line 13, we implemented multiply(), a method that returns the product, num2 x num1, of both properties.
In line 16, we implemented divide(), a method that returns the division of num2 by num1.