Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
__pycache__/calculator.cpython-312.pyc
__pycache__/test_calculator.cpython-312.pyc
*.exe
*.bin
*.o
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -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*.
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*.
40 changes: 29 additions & 11 deletions calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,32 +3,50 @@ 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!")
print("Example: addition: ", calc.add(1, 2))
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))
print("Example: modulo: ", calc.modulo(10, 3))
print("Example: power: ", calc.power(2, 3))