1. Create a class Student with attributes (name, roll, marks) and display details.
class Student:
def __init__(self, name, roll, marks):
[Link] = name
[Link] = roll
[Link] = marks
def display_details(self):
print("Student Details:")
print("Name:", [Link])
print("Roll No:", [Link])
print("Marks:", [Link])
# Creating object
s1 = Student("Rahul", 101, 85)
# Displaying details
s1.display_details()
2. Write a class Rectangle to calculate area and perimeter.
class Rectangle:
def __init__(self, length, width):
[Link] = length
[Link] = width
def area(self):
return [Link] * [Link]
def perimeter(self):
return 2 * ([Link] + [Link])
# Creating object
r1 = Rectangle(10, 5)
# Display results
print("Area:", [Link]())
print("Perimeter:", [Link]())
3. Create a class BankAccount with deposit and withdrawal methods.
class BankAccount:
def __init__(self, account_holder, balance=0):
self.account_holder = account_holder
[Link] = balance
def deposit(self, amount):
if amount > 0:
[Link] += amount
print("Deposited:", amount)
else:
print("Invalid deposit amount!")
def withdraw(self, amount):
if amount > [Link]:
print("Insufficient balance!")
elif amount <= 0:
print("Invalid withdrawal amount!")
else:
[Link] -= amount
print("Withdrawn:", amount)
def display_balance(self):
print("Current Balance:", [Link])
# Creating object
acc1 = BankAccount("Rahul", 1000)
# Performing operations
[Link](500)
[Link](300)
acc1.display_balance()
4. Design a class Employee to calculate salary with bonus.
class Employee:
def __init__(self, name, salary):
[Link] = name
[Link] = salary
def calculate_bonus(self, bonus_percent):
bonus = (bonus_percent / 100) * [Link]
return bonus
def total_salary(self, bonus_percent):
return [Link] + self.calculate_bonus(bonus_percent)
def display_details(self, bonus_percent):
print("Employee Name:", [Link])
print("Base Salary:", [Link])
print("Bonus:", self.calculate_bonus(bonus_percent))
print("Total Salary:", self.total_salary(bonus_percent))
# Creating object
emp1 = Employee("Anjali", 50000)
# Display details with 10% bonus
emp1.display_details(10)
5. Write a class Car with a constructor to initialize brand and price.
class Car:
def __init__(self, brand, price):
[Link] = brand
[Link] = price
def display_details(self):
print("Car Brand:", [Link])
print("Car Price:", [Link])
# Creating object
c1 = Car("Toyota", 800000)
# Display details
c1.display_details()
6. Create a class Book that uses default and parameterized constructors.
class Book:
def __init__(self, title="Unknown", author="Unknown", price=0):
[Link] = title
[Link] = author
[Link] = price
def display_details(self):
print("Title:", [Link])
print("Author:", [Link])
print("Price:", [Link])
print("----------------------")
# Using default constructor
b1 = Book()
b1.display_details()
# Using parameterized constructor
b2 = Book("Python Programming", "John Doe", 450)
b2.display_details()
7. Write a program demonstrating multiple objects creation for a class.
class Student:
def __init__(self, name, roll, marks):
[Link] = name
[Link] = roll
[Link] = marks
def display_details(self):
print("Name:", [Link], "| Roll No:", [Link], "| Marks:", [Link])
# Creating multiple objects
s1 = Student("Rahul", 101, 85)
s2 = Student("Anjali", 102, 90)
s3 = Student("Vikram", 103, 78)
# Displaying details
s1.display_details()
s2.display_details()
s3.display_details()
8. Create a class with:
a. Instance method to display data
b. Class method to count number of objects
class Student:
count = 0 # Class variable to count objects
def __init__(self, name):
[Link] = name
[Link] += 1 # Increment count when object is created
# Instance method
def display(self):
print("Student Name:", [Link])
# Class method
@classmethod
def display_count(cls):
print("Total Objects Created:", [Link])
# Creating objects
s1 = Student("Rahul")
s2 = Student("Anjali")
s3 = Student("Vikram")
# Calling instance method
[Link]()
[Link]()
[Link]()
# Calling class method
Student.display_count()
9. Write a class Product with:
a. Instance method → calculate discount
b. Class method → update tax rate
class Product:
tax_rate = 5 # Class variable (in percentage)
def __init__(self, name, price):
[Link] = name
[Link] = price
# Instance method → calculate discount
def calculate_discount(self, discount_percent):
discount = (discount_percent / 100) * [Link]
return [Link] - discount
# Class method → update tax rate
@classmethod
def update_tax_rate(cls, new_tax):
cls.tax_rate = new_tax
def final_price(self, discount_percent):
discounted_price = self.calculate_discount(discount_percent)
tax = (Product.tax_rate / 100) * discounted_price
return discounted_price + tax
# Creating object
p1 = Product("Laptop", 50000)
# Applying discount
print("Price after discount:", p1.calculate_discount(10))
# Updating tax rate
Product.update_tax_rate(12)
# Final price after discount + tax
print("Final Price (with tax):", p1.final_price(10))
10. Implement __str__() method for a class Student.
class Student:
def __init__(self, name, roll, marks):
[Link] = name
[Link] = roll
[Link] = marks
def __str__(self):
return f"Name: {[Link]}, Roll No: {[Link]}, Marks: {[Link]}"
# Creating object
s1 = Student("Rahul", 101, 85)
# Printing object
print(s1)
11. Write a program to handle division by zero.
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed!")
except ValueError:
print("Error: Please enter valid numeric values!")
12. Use finally block to display a message after execution.
try:
num1 = int(input("Enter numerator: "))
num2 = int(input("Enter denominator: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed!")
except ValueError:
print("Error: Invalid input!")
finally:
print("Execution completed (This always runs).")
13. Write a program that handles:
a. ZeroDivisionError
b. ValueError
c. TypeError
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Please enter numbers only.")
except TypeError:
print("Error: Type mismatch occurred!")
finally:
print("Program execution completed.")
14. Demonstrate single except block for multiple exceptions.
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
print("Result:", result)
except (ZeroDivisionError, ValueError, TypeError) as e:
print("Error occurred:", e)
finally:
print("Execution completed.")
15. Write a program that raises an exception if:
a. Age < 18
try:
age = int(input("Enter your age: "))
if age < 18:
raise Exception("You must be at least 18 years old!")
print("Access granted.")
except Exception as e:
print("Error:", e)
16. Create a function that raises exception for invalid password.
def validate_password(password):
if len(password) < 6:
raise Exception("Password must be at least 6 characters long!")
if not any([Link]() for char in password):
raise Exception("Password must contain at least one digit!")
if not any([Link]() for char in password):
raise Exception("Password must contain at least one uppercase letter!")
return "Password is valid"
# Main program
try:
pwd = input("Enter password: ")
result = validate_password(pwd)
print(result)
except Exception as e:
print("Error:", e)
17. Write a function that:
a. Accepts input
b. Handles exceptions internally
c. Returns result
def divide_numbers():
try:
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
result = num1 / num2
return result
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
return None
except ValueError:
print("Error: Invalid input!")
return None
# Calling function
output = divide_numbers()
if output is not None:
print("Result:", output)
18. Create a calculator function with proper exception handling.
def calculator():
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
op = input("Enter operator (+, -, *, /): ")
if op == '+':
return num1 + num2
elif op == '-':
return num1 - num2
elif op == '*':
return num1 * num2
elif op == '/':
return num1 / num2
else:
raise ValueError("Invalid operator!")
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
return None
except ValueError as e:
print("Error:", e)
return None
except TypeError:
print("Error: Type mismatch!")
return None
# Calling function
result = calculator()
if result is not None:
print("Result:", result)
19. Write a banking program using custom exceptions.
# Custom Exception
class InsufficientBalanceError(Exception):
pass
class BankAccount:
def __init__(self, name, balance):
[Link] = name
[Link] = balance
def deposit(self, amount):
if amount <= 0:
print("Invalid deposit amount!")
else:
[Link] += amount
print("Deposited:", amount)
def withdraw(self, amount):
if amount > [Link]:
raise InsufficientBalanceError("Insufficient balance!")
elif amount <= 0:
print("Invalid withdrawal amount!")
else:
[Link] -= amount
print("Withdrawn:", amount)
def display_balance(self):
print("Current Balance:", [Link])
# Main Program
try:
acc = BankAccount("Rahul", 1000)
[Link](500)
[Link](2000) # This will raise exception
acc.display_balance()
except InsufficientBalanceError as e:
print("Error:", e)