Implement a class Calculator
with a private attribute for the current value. Include methods for basic operations while ensuring that certain erroneous operations (e.g., division by zero) are handled appropriately.
Example 1:
Input: 10, "+", 5 Output: 15
Example 2:
Input: 5, "/", 0 Output: "Division by zero error"
You can use exception handling to catch and handle division by zero errors.
<pre>
class Calculator:
def __init__(self, initial_value=0):
self._current_value = initial_value
def add(self, value):
self._current_value += value
def subtract(self, value):
self._current_value -= value
def multiply(self, value):
self._current_value *= value
def divide(self, value):
try:
self._current_value /= value
except ZeroDivisionError:
return “Division by zero error”
def get_current_value(self):
return self._current_value
# Test the class
calculator = Calculator(10)
calculator.add(5)
print(calculator.get_current_value()) # Output: 15
calculator.divide(0) # Output: Division by zero error
</pre>
Unlock AI & Data Science treasures. Log in!