diff --git a/.gitignore b/.gitignore index 520fc7e..f97ae69 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,5 @@ __pycache__/calculator.cpython-312.pyc __pycache__/test_calculator.cpython-312.pyc +*.exe +*.bin +*.o diff --git a/README.md b/README.md index c8a6302..3f393d8 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,3 @@ # python-calculator -This is a very simple calculator program for learning how to write unit tests in Python. It contains a Calculator class (*calculator.py*) which perform 4 mathematic operations: add, subtract, multiply, and divide. You have to add unit test cases to test them in the file *test_calculator.py*. \ No newline at end of file +This is a very simple calculator program for learning how to write unit tests in Python. It contains a Calculator class (*calculator.py*) which perform 5 mathematic operations: add, subtract, multiply, power, and divide. You have to add unit test cases to test them in the file *test_calculator.py*. diff --git a/calculator.py b/calculator.py index 306879a..e45735f 100644 --- a/calculator.py +++ b/calculator.py @@ -3,27 +3,44 @@ def add(self, a, b): return a + b def subtract(self, a, b): - return b - a + return a - b def multiply(self, a, b): result = 0 - for i in range(b+1): + for _ in range(abs(b)): result = self.add(result, a) - return result + return result if b >= 0 else -result def divide(self, a, b): + if b == 0: + raise ZeroDivisionError("Division by zero") + sign = -1 if (a < 0) ^ (b < 0) else 1 + a, b = abs(a), abs(b) result = 0 - while a > b: + while a >= b: a = self.subtract(a, b) result += 1 - return result - + return result * sign + def modulo(self, a, b): - while a <= b: - a = a-b - return a + if b == 0: + raise ZeroDivisionError("Modulo by zero") + sign = -1 if a < 0 else 1 + a, b = abs(a), abs(b) + while a >= b: + a = self.subtract(a, b) + return a * sign + + def power(self, a, b): + if b == 0: + return 1 + if b < 0: + return 1 / self.power(a, -b) + result = 1 + for _ in range(b): + result = self.multiply(result, a) + return result -# Example usage: if __name__ == "__main__": calc = Calculator() print("This is a simple calculator class!") @@ -31,4 +48,5 @@ def modulo(self, a, b): print("Example: subtraction: ", calc.subtract(4, 2)) print("Example: multiplication: ", calc.multiply(2, 3)) print("Example: division: ", calc.divide(10, 2)) - print("Example: modulo: ", calc.modulo(10, 3)) \ No newline at end of file + print("Example: modulo: ", calc.modulo(10, 3)) + print("Example: power: ", calc.power(2, 3))