|
| 1 | +# Class with Method Task: Create a class Calculator with methods add, subtract, multiply, and divide. Create an object and call each method with example numbers. |
| 2 | + |
| 3 | +class Calculator: |
| 4 | + # Method for addition |
| 5 | + def add(self, a, b): |
| 6 | + return a + b |
| 7 | + |
| 8 | + # Method for subtraction |
| 9 | + def subtract(self, a, b): |
| 10 | + return a - b |
| 11 | + |
| 12 | + # Method for multiplication |
| 13 | + def multiply(self, a, b): |
| 14 | + return a * b |
| 15 | + |
| 16 | + # Method for division |
| 17 | + def divide(self, a, b): |
| 18 | + if b == 0: |
| 19 | + return "Error! Division by zero." |
| 20 | + return a / b |
| 21 | + |
| 22 | + |
| 23 | +# Create an object of Calculator class |
| 24 | +calc = Calculator() |
| 25 | + |
| 26 | +# Example calls |
| 27 | +print("Addition:", calc.add(10, 5)) |
| 28 | +print("Subtraction:", calc.subtract(10, 5)) |
| 29 | +print("Multiplication:", calc.multiply(10, 5)) |
| 30 | +print("Division:", calc.divide(10, 5)) |
0 commit comments