Recap - Simple Calculator
Part of the Object Oriented Programming section of Coddy's Python journey — lesson 8 of 64.
Challenge
MediumYour Calculator class in calculator.py should:
- Have a constructor that initializes a
resultattribute to 0 - Include methods for
add,subtract,multiply, anddividethat each:- Take a number as an argument
- Perform the operation between the current
resultand the number - Update the
resultattribute - Return the new result
- Include a
clearmethod that resets theresultto 0 - Include a
get_resultmethod that returns the current result - For the
dividemethod, you must handle division by zero by:- Checking if the provided number equals 0
- If it is zero, print exactly: "Error: Division by zero"
- Leave the
resultattribute unchanged in this case - Return the unchanged
resultvalue
The driver.py file will import your Calculator class and test it with code similar to this:
from calculator import Calculator
calc = Calculator()
calc.add(5) # result becomes 5
calc.multiply(3) # result becomes 15
calc.subtract(2) # result becomes 13
calc.divide(0) # prints "Error: Division by zero", result remains 13
calc.divide(2) # result becomes 6.5
calc.clear() # result becomes 0Follow the TODO comments in the calculator.py file to implement all required functionality.
Cheat sheet
Create a Calculator class with basic arithmetic operations:
class Calculator:
def __init__(self):
self.result = 0
def add(self, number):
self.result += number
return self.result
def subtract(self, number):
self.result -= number
return self.result
def multiply(self, number):
self.result *= number
return self.result
def divide(self, number):
if number == 0:
print("Error: Division by zero")
return self.result
self.result /= number
return self.result
def clear(self):
self.result = 0
def get_result(self):
return self.resultUsage example:
calc = Calculator()
calc.add(5) # result becomes 5
calc.multiply(3) # result becomes 15
calc.divide(0) # prints error, result unchangedTry it yourself
from calculator import Calculator
# Test case handler
test_case = input()
if test_case == "constructor_test":
# Test calculator creation and initial state
calc = Calculator()
print(f"Initial result: {calc.get_result()}")
print("Calculator created successfully")
elif test_case == "addition_test":
# Test addition functionality
calc = Calculator()
result1 = calc.add(10)
print(f"After adding 10: {result1}")
result2 = calc.add(5)
print(f"After adding 5: {result2}")
print(f"Final result: {calc.get_result()}")
elif test_case == "subtraction_test":
# Test subtraction functionality
calc = Calculator()
calc.add(20) # Start with 20
result1 = calc.subtract(8)
print(f"After subtracting 8 from 20: {result1}")
result2 = calc.subtract(2)
print(f"After subtracting 2: {result2}")
print(f"Final result: {calc.get_result()}")
elif test_case == "multiplication_test":
# Test multiplication functionality
calc = Calculator()
calc.add(5) # Start with 5
result1 = calc.multiply(4)
print(f"After multiplying by 4: {result1}")
result2 = calc.multiply(2)
print(f"After multiplying by 2: {result2}")
print(f"Final result: {calc.get_result()}")
elif test_case == "division_test":
# Test division functionality
calc = Calculator()
calc.add(100) # Start with 100
result1 = calc.divide(4)
print(f"After dividing by 4: {result1}")
result2 = calc.divide(5)
print(f"After dividing by 5: {result2}")
print(f"Final result: {calc.get_result()}")
elif test_case == "division_by_zero_test":
# Test division by zero error handling
calc = Calculator()
calc.add(50)
print(f"Initial value: {calc.get_result()}")
result = calc.divide(0) # Should print error message
print(f"Result after division by zero: {result}")
print(f"Value unchanged: {calc.get_result()}")
elif test_case == "clear_test":
# Test clear functionality
calc = Calculator()
calc.add(25)
calc.multiply(3)
print(f"Before clear: {calc.get_result()}")
result = calc.clear()
print(f"After clear: {result}")
print(f"Current result: {calc.get_result()}")
elif test_case == "comprehensive_test":
# Test all operations in sequence
calc = Calculator()
# Perform a series of operations
calc.add(10) # result = 10
calc.multiply(3) # result = 30
calc.subtract(5) # result = 25
calc.divide(5) # result = 5
print(f"After sequence of operations: {calc.get_result()}")
# Test error handling
calc.divide(0) # Should print error
print(f"After division by zero attempt: {calc.get_result()}")
# Clear and start fresh
calc.clear()
calc.add(100)
print(f"After clear and add 100: {calc.get_result()}")
else:
print("Unknown test case")
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe self ParameterMethodsAttributesConstructor Method (__init__)Recap - Simple Calculator4Inheritance
Basic InheritanceThe super() FunctionMethod OverridingMultiple InheritanceMethod Resolution OrderRecap - Employee Hierarchy7Special Methods
Magic Methods IntroductionOperator OverloadingContainer Magic MethodsRecap - Custom List10Design Patterns Part 1
Intro to design patternSingleton PatternFactory PatternObserver PatternStrategy Pattern2Decorators
Introduction to DecoratorsProperty DecoratorStatic Method DecoratorClass Method Decorator5Polymorphism
Method Overriding RevisitedDuck TypingAbstract Classes and MethodsInterface DesignRecap - Shape Calculator8Advanced OOP Concepts
Composition vs InheritanceMixinsStatic and Class MethodsClass DecoratorsContext Managers3Class Properties
Instance vs Class VariablesProperty DecoratorsPrivate AttributesRecap - Bank Account Manager6Encapsulation
Public, Protected, Private MemAccess ModifiersInformation HidingProperty Decorators AdvancedRecap - Student Records System12Project: Library Management
Project OverviewBook and User Classes