Lab_Assignment lab 3
Lab_Assignment lab 3
Programming
Q1: Class Numbers
Create a class named Numbers. The class should have two member variables a and b. Define
methods to:
• Initialize a and b from user input.
• Add two numbers and display the result.
• Multiply two numbers and display the result.
• Subtract two numbers and display the result.
• Call these functions in the main program using an object of the Numbers class.
Code:
class Numbers:
def __init__(self, a, b):
self.a = a
self.b = b
def add(self):
return self.a + self.b
def multiply(self):
return self.a * self.b
def subtract(self):
return self.a - self.b
# Main program
a = float(input("Enter first number (a): "))
b = float(input("Enter second number (b): "))
num = Numbers(a, b)
print(f"Addition: {num.add()}")
print(f"Multiplication: {num.multiply()}")
print(f"Subtraction: {num.subtract()}")
Sample Output:
Code:
class Complex:
def __init__(self, real, imag):
self.real = real
self.imag = imag
def display(self):
sign = '+' if self.imag >= 0 else ''
return f"{self.real} {sign} {self.imag}i"
# Main program
r1 = float(input("Enter real part of first complex number: "))
i1 = float(input("Enter imaginary part of first complex number: "))
r2 = float(input("Enter real part of second complex number: "))
i2 = float(input("Enter imaginary part of second complex number:
"))
c1 = Complex(r1, i1)
c2 = Complex(r2, i2)
print(f"Addition: {c1.add(c2).display()}")
print(f"Subtraction: {c1.subtract(c2).display()}")
print(f"Multiplication: {c1.multiply(c2).display()}")
Sample Output: