Python Assignment-3,4
Python Assignment-3,4
class cal():
def __init__(self,a,b):
self.a=a
self.b=b
def add(self):
return self.a+self.b
def mul(self):
return self.a*self.b
def div(self):
return self.a/self.b
def sub(self):
return self.a-self.b
a=int(input("Enter first number: "))
b=int(input("Enter second number: "))
obj=cal(a,b)
choice=1
while choice!=0:
print("0. Exit")
print("1. Add")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
choice=int(input("Enter choice: "))
if choice==1:
print("Result: ",obj.add())
elif choice==2:
print("Result: ",obj.sub())
elif choice==3:
print("Result: ",obj.mul())
elif choice==4:
print("Result: ",round(obj.div(),2))
elif choice==0:
print("Exiting!")
else:
print("Invalid choice!!")
print()
Output
class Election:
def __init__(self):
self.votes = defaultdict(int)
def find_max_votes(self):
max_votes = max(self.votes.values())
max_vote_candidates = [candidate for candidate, votes in self.votes.items() if votes ==
max_votes]
max_vote_candidates.sort()
return max_vote_candidates[0]
election = Election()
# Cast votes
election.cast_vote("John")
election.cast_vote("Jane")
election.cast_vote("John")
election.cast_vote("Michael")
election.cast_vote("Jane")
election.cast_vote("Michael")
election.cast_vote("John")
Output
3. Create Birthday Reminder Application to notify users using file handling and exception
Handling.
import datetime
class BirthdayReminder:
def __init__(self, file_name):
self.file_name = file_name
def get_today_birthdays(self):
today = datetime.date.today().strftime("%m-%d")
birthdays = []
with open(self.file_name, "r") as file:
for line in file:
name, date = line.strip().split(":")
if date == today:
birthdays.append(name)
return birthdays
def notify_birthdays(self):
try:
birthdays = self.get_today_birthdays()
if len(birthdays) == 0:
print("No birthdays today.")
else:
print("Birthdays today:")
for name in birthdays:
print(name)
except FileNotFoundError:
print("No birthdays recorded yet.")
reminder = BirthdayReminder("birthdays.txt")
while True:
print("\n*** Birthday Reminder Application ***")
print("1. Add a birthday")
print("2. Notify birthdays today")
print("3. Exit")
choice = input("Enter your choice: ")
Output
class Time:
def __init__(self, hrs, mins):
self.hrs = hrs
self.mins = mins
def addTime(self, other):
total_minutes = self.hrs * 60 + self.mins + other.hrs * 60 + other.mins
hrs = total_minutes // 60
mins = total_minutes % 60
Output
5. Write a Python class which has two methods get_String and print_String. get_String accept a
string from the user and print_String print the string in upper case.
class StringManipulator:
def __init__(self):
self.string = ""
def get_String(self):
self.string = input("Enter a string: ")
def print_String(self):
print("String in upper case:")
print(self.string.upper())
manipulator = StringManipulator()
manipulator.get_String()
manipulator.print_String()
6. Create a class “GrandMother” with a subclass “Mother” with a subclass “Daughter”. All
the three classes to have there own constructors. The object of only “Daughter” class to
be made to fetch all the details of Grandmother and mother.
class GrandMother:
def __init__(self, grandmother_name):
self.grandmother_name = grandmother_name
class Mother(GrandMother):
def __init__(self, grandmother_name, mother_name):
super().__init__(grandmother_name)
self.mother_name = mother_name
class Daughter(Mother):
def __init__(self, grandmother_name, mother_name, daughter_name):
super().__init__(grandmother_name, mother_name)
self.daughter_name = daughter_name
def get_details(self):
print("Grandmother:", self.grandmother_name)
print("Mother:", self.mother_name)
print("Daughter:", self.daughter_name)
grandmother_name = input("Enter grandmother's name: ")
mother_name = input("Enter mother's name: ")
daughter_name = input("Enter daughter's name: ")
daughter = Daughter(grandmother_name, mother_name, daughter_name)
daughter.get_details()
Output
class Parent:
def __init__(self, name, age):
self.name = name
self.age = age
def print_details(self):
print("Name:", self.name)
print("Age:", self.age)
class Child(Parent):
def __init__(self, name, age):
super().__init__(name, age)
self.print_details()
name = input("Enter parent's name: ")
age = int(input("Enter parent's age: "))
child = Child(name, age)
Output
8. Write a program to create an abstract class “Animal” that holds three declaration functions
based on their characteristics. Create four subclasses – “Mammals”, “Reptiles”, “birds”, and
“amphibians” inherited from “Animal” class.
@abstractmethod
def locomotion(self):
pass
class Mammals(Animal):
def sound(self):
return "Mammals produce various sounds."
def habitat(self):
if animal_type == "mammals":
animal = Mammals()
elif animal_type == "reptiles":
animal = Reptiles()
elif animal_type == "birds":
animal = Birds()
elif animal_type == "amphibians":
animal = Amphibians()
else:
print("Invalid animal type entered.")
exit()
print(animal.sound())
print(animal.habitat())
print(animal.locomotion())
Output
class ATM:
def __init__(self):
self.accounts = []
def add_account(self, account):
self.accounts.append(account)
def authenticate_user(self, account_number, pin):
for account in self.accounts:
if account.account_number == account_number and account.pin == pin:
return account
return None
def display_menu(self):
print("ATM Menu:")
print("1. Check Balance")
print("2. Withdraw Money")
print("3. Deposit Money")
print("4. Exit")
def run(self):
print("Welcome to the ATM!")
account_number = input("Enter your account number: ")
pin = input("Enter your PIN: ")
class Account:
def __init__(self, account_number, pin, balance=0.0):
self.account_number = account_number
self.pin = pin
self.balance = balance
atm = ATM()
atm.run()
Output
class ListOperations:
def __init__(self):
self.my_list = [1,4,5]
def append_element(self, element):
self.my_list.append(element)
print("Element appended successfully.")
def delete_element(self, element):
if element in self.my_list:
self.my_list.remove(element)
print("Element deleted successfully.")
else:
print("Element not found in the list.")
def display_list(self):
if self.my_list:
print("Elements in the list:")
for element in self.my_list:
print(element)
else:
print("List is empty.")
list_operations = ListOperations()
while True:
print("\n--- List Operations Menu ---")
print("1. Append element")
print("2. Delete element")
print("3. Display list")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
element = input("Enter the element to append: ")
list_operations.append_element(element)
elif choice == "2":
element = input("Enter the element to delete: ")
list_operations.delete_element(element)
elif choice == "3":
list_operations.display_list()
elif choice == "4":
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
import numpy as np
a = np.array([[10,40],[30,20]])
print("Original array:")
print(a)
print("Sort the array along the first axis:")
print(np.sort(a, axis=0))
print("Sort the array along the last axis:")
print(np.sort(a))
print("Sort the flattened array:")
print(np.sort(a, axis=None))
Output
2. Write a NumPy program to capitalize the first letter, lowercase, uppercase, swapcase, title-case
of all the elements of a given array.
import numpy as np
x = np.array(['python', 'REACT', 'ooSE', 'dsa'])
print("Original Array:")
print(x)
capitalized_case = np.char.capitalize(x)
lowered_case = np.char.lower(x)
uppered_case = np.char.upper(x)
swapcased_case = np.char.swapcase(x)
titlecased_case = np.char.title(x)
print("\nCapitalized: ", capitalized_case)
print("Lowered: ", lowered_case)
print("Uppered: ", uppered_case)
print("Swapcased: ", swapcased_case)
print("Titlecased: ", titlecased_case)
3. Write a Pandas program to display the default index and set a column as an Index in a given
dataframe.
import pandas as pd
df = pd.DataFrame({
'Name':['Jai', 'Princi', 'Gaurav', 'Anuj', 'Geeku'],
'Age':[27, 24, 22, 32, 15],
'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj', 'Noida'],
'Qualification':['Msc', 'MA', 'MCA', 'Phd', '10th'],
't_id':['t1', 't2', 't3', 't4', 't5']})
print("Default Index:")
print(df)
print("\nt_id as new Index:")
df1 = df.set_index('t_id')
print(df1)
Output
import pandas as pd
student_data1 = pd.DataFrame({
'student_id': ['S1', 'S2', 'S3', 'S4'],
'name': ['Rahul', 'Shubham', 'Ravi', 'Hrithik'],
'marks': [200, 210, 190, 222]})
student_data2 = pd.DataFrame({
'student_id': ['S4', 'S5', 'S6', 'S7'],
'name': ['Scarlette', 'Williamson', 'Smith', 'Cook'],
'marks': [201, 200, 198, 219]})
exam_data = pd.DataFrame({
'student_id': ['S1', 'S2', 'S3', 'S4', 'S5', 'S7', 'S8', 'S9', 'S10'],
'exam_id': [23, 45, 12, 67, 21, 55, 33, 14, 56]})
print("Original DataFrames:")
print(student_data1)
print(student_data2)
print(exam_data)
Output
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
sales_data.csv:
Date,Sales,Category
2023-01-01,12500,Electronics
2023-02-02,32500,Clothing
2023-03-03,52200,Home Goods
2023-04-04,22600,Electronics
2023-05-05,13400,Clothing
2023-06-06,52350,Home Goods
2023-07-07,44550,Electronics
2023-08-08,13250,Clothing
2023-09-09,13150,Home Goods
2023-10-10,20450,Electronics
Output:
import tkinter as tk
from datetime import date
def calculate_age():
birth_date = date(int(year_entry.get()), int(month_entry.get()), int(day_entry.get()))
today = date.today()
age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month,
birth_date.day))
result_label.config(text="Your age is: {} years".format(age))
window.mainloop()
Output
employees = [
{"first_name": "John", "last_name": "Doe", "salary": 50000, "department_number": 1},
{"first_name": "Jane", "last_name": "Smith", "salary": 60000, "department_number": 2},
{"first_name": "Michael", "last_name": "Johnson", "salary": 55000, "department_number": 1},
{"first_name": "Emily", "last_name": "Brown", "salary": 70000, "department_number": 3},
{"first_name": "Daniel", "last_name": "Davis", "salary": 45000, "department_number": 2},
]
Output