import numpy as np
# Creating two matrices
A = np.array([[4, 8], [6, 10]])
B = np.array([[2, 4], [3, 5]])
print("Matrix A:\n", A)
print("Matrix B:\n", B)
# Matrix Addition
print("\nMatrix Addition:\n", A + B)
# Matrix Subtraction
print("\nMatrix Subtraction:\n", A - B)
# Element-wise Multiplication
print("\nElement-wise Multiplication:\n", A * B)
# Matrix Multiplication (Dot Product)
print("\nMatrix Multiplication (Dot Product):\n", np.dot(A, B))
# Element-wise Division
print("\nElement-wise Division:\n", A / B)
# Taking input from user
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
# Concatenating strings
result = str1 + " " + str2
print("\nConcatenated String:", result)
3.import numpy as np
# Generating six random integers between 10 and 30
random_numbers = np.random.randint(10, 31, size=6)
print("Random Numbers:", random_numbers)
4 class PrintValue:
def display(self, a=None, b=None):
if isinstance(a, int) and isinstance(b, str):
print(f"Integer: {a}, Character: {b}")
elif isinstance(a, str) and isinstance(b, int):
print(f"Character: {a}, Integer: {b}")
else:
print("Invalid input!")
# Creating object
obj = PrintValue()
# Calling methods with different parameter sequences
obj.display(10, 'A') # Integer first, then character
obj.display('B', 20) # Character first, then integer
class Shape:
def area(self, length, breadth=None):
if breadth is None: # If only one parameter is passed, calculate area of square
print(f"Area of Square: {length * length}")
else: # If two parameters are passed, calculate area of rectangle
print(f"Area of Rectangle: {length * breadth}")
# Creating object
shape = Shape()
# Calculating areas
shape.area(5) # Square (side = 5)
shape.area(4, 6) # Rectangle (length = 4, breadth = 6)
6
class Degree:
def getDegree(self):
print("I got a degree")
class Undergraduate(Degree):
def getDegree(self):
print("I am an Undergraduate")
class Postgraduate(Degree):
def getDegree(self):
print("I am a Postgraduate")
# Creating objects of each class
deg = Degree()
ug = Undergraduate()
pg = Postgraduate()
# Calling the method
deg.getDegree() # Calls the method in Degree class
ug.getDegree() # Calls the overridden method in Undergraduate class
pg.getDegree()
7
class Employee:
def __init__(self, name, department, salary):
self.name = name
self.department = department
self.salary = salary
def display_info(self):
print(f"Employee Name: {self.name}")
print(f"Department: {self.department}")
print(f"Salary: {self.salary}")
# Taking input from user
name = input("Enter Employee Name: ")
department = input("Enter Department: ")
salary = float(input("Enter Salary: "))
# Creating Employee object
emp = Employee(name, department, salary)
print("\nEmployee Information:")
emp.display_info()
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display_person(self):
print(f"Name: {self.name}")
print(f"Age: {self.age}")
class Student(Person): # Inheriting from Person
def __init__(self, name, age, roll_no, course):
super().__init__(name, age)
self.roll_no = roll_no
self.course = course
def display_student(self):
self.display_person()
print(f"Roll Number: {self.roll_no}")
print(f"Course: {self.course}")
# Taking input from user
name = input("Enter Student Name: ")
age = int(input("Enter Age: "))
roll_no = input("Enter Roll Number: ")
course = input("Enter Course: ")
# Creating Student object
stud = Student(name, age, roll_no, course)
print("\nStudent Information:")
stud.display_student()
class Teacher:
def __init__(self, subject):
self.subject = subject
def display_subject(self):
print(f"Teaches: {self.subject}")
class Researcher:
def __init__(self, research_topic):
self.research_topic = research_topic
def display_research(self):
print(f"Research Topic: {self.research_topic}")
# Multiple Inheritance
class Professor(Teacher, Researcher):
def __init__(self, name, subject, research_topic):
Teacher.__init__(self, subject)
Researcher.__init__(self, research_topic)
self.name = name
def display_info(self):
print(f"Professor Name: {self.name}")
self.display_subject()
self.display_research()
# Taking input from user
name = input("Enter Professor Name: ")
subject = input("Enter Subject: ")
research_topic = input("Enter Research Topic: ")
# Creating Professor object
prof = Professor(name, subject, research_topic)
print("\nProfessor Information:")
prof.display_info()
1. Check for ZeroDivisionError Exception
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
print(f"Result: {result}")
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except ValueError:
print("Error: Please enter valid numeric values.")
Example Output:
Enter numerator: 10
Enter denominator: 0
Error: Division by zero is not allowed.
2. User-Defined Exception for Password Validation
class PasswordError(Exception):
def __init__(self, message="Invalid password! Password must be at least 6 characters
long."):
self.message = message
super().__init__(self.message)
def check_password(password):
if len(password) < 6:
raise PasswordError
else:
print("Password is valid.")
try:
user_password = input("Enter your password: ")
check_password(user_password)
except PasswordError as e:
print(e)
Example Output:
Enter your password: 123
Invalid password! Password must be at least 6 characters long.
Enter your password: secure123
Password is valid.