The following code contains a logical error. Can you find out what it is?
class BasicCalculator:
def __init__(self):
pass
def add(self, a, b):
"""Returns the sum of a and b."""
print(a + b)
def subtract(self, a, b):
"""Returns the difference between a and b."""
print(a - b)
def multiply(self, a, b):
"""Returns the product of a and b."""
print(a * b)
def divide(self, a, b):
"""Returns the quotient of a divided by b."""
if b != 0:
print(a / b)
else:
print("Error: Division by zero")
# Test the BasicCalculator class
if __name__ == "__main__":
calculator = BasicCalculator()
result = calculator.add(3, 5)
print("Addition result:", result) # Expected output: Addition result: 8
result = calculator.subtract(10, 4)
print("Subtraction result:", result) # Expected output: Subtraction result: 6
result = calculator.multiply(2, 3)
print("Multiplication result:", result) # Expected output: Multiplication result: 6
result = calculator.divide(8, 2)
print("Division result:", result) # Expected output: Division result: 4.0
result = calculator.divide(8, 0)
print("Division result:", result) # Expected output: Error: Division by zero
For each of the functions in the BasicCalculator class, the print statements should be changed to return statements.
For example:
def subtract(self, a, b):
"""Returns the difference between a and b."""
print(a - b)
should be changed to:
def subtract(self, a, b):
"""Returns the difference between a and b."""
return(a - b)
The "returned" value will then be printed correctly supplied to result and printed when the function is called as below:
result = calculator.subtract(10, 4)
print("Subtraction result:", result)
Using return this the expected output as mentioned by Carl Wagner
Addition result: 8
Subtraction result: 6
Multiplication result: 6
Division result: 4.0
Division result: Error: Division by zero
[Done] exited with code=0 in 0.06 seconds