0% found this document useful (0 votes)
51 views

Python Assignment-3,4

The document contains 8 programming assignments involving classes and objects in Python: 1. Create a basic calculator class with methods to add, subtract, multiply and divide two numbers. 2. Create an election class to track votes for candidates and find the winner. 3. Create a birthday reminder application using a class to store birthdays in a file and notify users of upcoming birthdays. The remaining assignments involve creating various classes to represent relationships between objects, abstract base classes, and subclasses to model real-world scenarios like families and animal types.

Uploaded by

Nobita
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

Python Assignment-3,4

The document contains 8 programming assignments involving classes and objects in Python: 1. Create a basic calculator class with methods to add, subtract, multiply and divide two numbers. 2. Create an election class to track votes for candidates and find the winner. 3. Create a birthday reminder application using a class to store birthdays in a file and notify users of upcoming birthdays. The remaining assignments involve creating various classes to represent relationships between objects, abstract base classes, and subclasses to model real-world scenarios like families and animal types.

Uploaded by

Nobita
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Assignment – III

1. Create a Class which Performs Basic Calculator Operations.

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

Parv Jain Page | 16 09714004422


2. Every time a vote is cast the name of the candidate is appended to the data structure. Print the
names of candidates who received maximum vote in lexicographical order and if there is a tie print
lexicographically smaller name.

from collections import defaultdict

class Election:
def __init__(self):
self.votes = defaultdict(int)

def cast_vote(self, candidate_name):


self.votes[candidate_name] += 1

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")

Parv Jain Page | 17 09714004422


max_vote_candidate = election.find_max_votes()
print("Candidates with Maximum Votes in Lexicographical Order:")
print(max_vote_candidate)

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 add_birthday(self, name, date):


with open(self.file_name, "a") as file:
file.write(f"{name}:{date}\n")

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: ")

Parv Jain Page | 18 09714004422


if choice == "1":
name = input("Enter the name: ")
date = input("Enter the birthday (MM-DD): ")
try:
datetime.datetime.strptime(date, "%m-%d")
reminder.add_birthday(name, date)
print("Birthday added successfully.")
except ValueError:
print("Invalid date format. Please enter the birthday in MM-DD format.")
elif choice == "2":
reminder.notify_birthdays()
elif choice == "3":
break
else:
print("Invalid choice. Please select a valid option.")

Output

4. Create a class “Time” and initialize it with hrs and mins.


1. Make a method addTime which should take two time object and add them. E.g.- (6
hour and 35 min)+(2 hr and 12 min) is (8 hr and 47 min)
2. Make a method showTime which should print the time.
3. Make a method showMinute which should display the total minutes in the Time. E.g.-
(2 hr 6 min) should display 126 minutes.

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

Parv Jain Page | 19 09714004422


return Time(hrs, mins)
def showTime(self):
print(f"{self.hrs} hr and {self.mins} min")
def showMinute(self):
total_minutes = self.hrs * 60 + self.mins
print(f"Total minutes: {total_minutes}")
hrs1 = int(input("Enter the hours for the first time: "))
mins1 = int(input("Enter the minutes for the first time: "))
time1 = Time(hrs1, mins1)
hrs2 = int(input("Enter the hours for the second time: "))
mins2 = int(input("Enter the minutes for the second time: "))
time2 = Time(hrs2, mins2)
time_sum = time1.addTime(time2)
print("Time 1:")
time1.showTime()
print("Time 2:")
time2.showTime()
print("Sum of Times:")
time_sum.showTime()
time_sum.showMinute()

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()

Parv Jain Page | 20 09714004422


Output

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

Parv Jain Page | 21 09714004422


7. Create a class “Parent” and a subclass “Child”. The “Parent” holds a constructor with two
parameters name and age and also one method print() that prints name and age. The “child to
have only one constructor that send the value to parent constructor and calls print() from its
constructor only. Note: the object of only “Child” class to be created.

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.

from abc import ABC, abstractmethod


class Animal(ABC):
@abstractmethod
def sound(self):
pass
@abstractmethod
def habitat(self):
pass

@abstractmethod
def locomotion(self):
pass

class Mammals(Animal):
def sound(self):
return "Mammals produce various sounds."
def habitat(self):

Parv Jain Page | 22 09714004422


return "Mammals inhabit diverse ecosystems."
def locomotion(self):
return "Mammals have different modes of locomotion."
class Reptiles(Animal):
def sound(self):
return "Reptiles produce various sounds."
def habitat(self):
return "Reptiles are found in a variety of habitats."
def locomotion(self):
return "Reptiles move using different methods."
class Birds(Animal):
def sound(self):
return "Birds produce a wide range of sounds."
def habitat(self):
return "Birds inhabit various types of habitats."
def locomotion(self):
return "Birds have diverse modes of locomotion."
class Amphibians(Animal):
def sound(self):
return "Amphibians produce distinct sounds."
def habitat(self):
return "Amphibians occupy different habitats."
def locomotion(self):
return "Amphibians have unique locomotion mechanisms."
animal_type = input("Enter the type of animal (Mammals/Reptiles/Birds/Amphibians): ").lower()

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

Parv Jain Page | 23 09714004422


9. Implement ATM simulation system displaying its operations using object oriented features.

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: ")

account = self.authenticate_user(account_number, pin)


if account:
print("Authentication successful!")
while True:
self.display_menu()
choice = input("Enter your choice: ")
if choice == "1":
account.check_balance()
elif choice == "2":
amount = float(input("Enter the amount to withdraw: "))
account.withdraw_money(amount)
elif choice == "3":
amount = float(input("Enter the amount to deposit: "))
account.deposit_money(amount)
elif choice == "4":
print("Thank you for using the ATM!")
break
else:
print("Invalid choice. Please try again.")
else:
print("Authentication failed. Invalid account number or PIN.")

class Account:
def __init__(self, account_number, pin, balance=0.0):
self.account_number = account_number
self.pin = pin
self.balance = balance

Parv Jain Page | 24 09714004422


def check_balance(self):
print("Your current balance is:", self.balance)

def withdraw_money(self, amount):


if self.balance >= amount:
self.balance -= amount
print("Amount withdrawn:", amount)
print("Remaining balance:", self.balance)
else:
print("Insufficient funds. Unable to withdraw the amount.")

def deposit_money(self, amount):


self.balance += amount
print("Amount deposited:", amount)
print("Updated balance:", self.balance)

atm = ATM()

account1 = Account("4863567890", "2546", 1520.0)


account2 = Account("3546845365", "1542", 1489.0)
atm.add_account(account1)
atm.add_account(account2)

atm.run()

Output

Parv Jain Page | 25 09714004422


10. Python Program to Append, Delete and Display Elements of a List Using Classes.

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.")

Parv Jain Page | 26 09714004422


Output

Parv Jain Page | 27 09714004422


Assignment – IV
1. Write a NumPy program to sort a given array of shape 2 along the first axis, last axis and on
flattened array.

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)

Parv Jain Page | 28 09714004422


Output

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

Parv Jain Page | 29 09714004422


4. Write a Pandas program to join the two given dataframes along rows and merge with another
dataframe along the common column id.

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)

print("\nJoin first two said dataframes along rows:")


result_data = pd.concat([student_data1, student_data2])
print(result_data)

print("\nNow join the said result_data and df_exam_data along student_id:")


final_merged_data = pd.merge(result_data, exam_data, on='student_id')
print(final_merged_data)

Output

Parv Jain Page | 30 09714004422


5. Analyze the sales data and visualize it using different plots.

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Load the sales data into a DataFrame


sales_data = pd.read_csv('sales_data.csv')

# Analyze the sales data


# Example 1: Total sales by month
sales_data['Date'] = pd.to_datetime(sales_data['Date'])
sales_data['Month'] = sales_data['Date'].dt.month
total_sales_by_month = sales_data.groupby('Month')['Sales'].sum()

# Example 2: Sales by product category


sales_by_category = sales_data.groupby('Category')['Sales'].sum()

# Visualize the sales data


# Example 1: Bar plot of total sales by month
plt.figure(figsize=(8, 6))
sns.barplot(x=total_sales_by_month.index, y=total_sales_by_month.values)
plt.xlabel('Month')
plt.ylabel('Total Sales')
plt.title('Total Sales by Month')
plt.show()

# Example 2: Pie chart of sales by product category


plt.figure(figsize=(8, 6))
plt.pie(sales_by_category, labels=sales_by_category.index, autopct='%1.1f%%')
plt.title('Sales by Product Category')

Parv Jain Page | 31 09714004422


plt.axis('equal')
plt.show()

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:

Parv Jain Page | 32 09714004422


6. Create age calculator application using different GUI widgets.

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))

# Create the main window


window = tk.Tk()
window.title("Age Calculator")

# Create and place the input labels and entry fields


day_label = tk.Label(window, text="Day:")
day_label.pack()
day_entry = tk.Entry(window)
day_entry.pack()

month_label = tk.Label(window, text="Month:")


month_label.pack()
month_entry = tk.Entry(window)
month_entry.pack()

year_label = tk.Label(window, text="Year:")


year_label.pack()
year_entry = tk.Entry(window)
year_entry.pack()

# Create and place the calculate button


calculate_button = tk.Button(window, text="Calculate Age", command=calculate_age)
calculate_button.pack()

# Create and place the result label


result_label = tk.Label(window, text="")
result_label.pack()

window.mainloop()

Output

Parv Jain Page | 33 09714004422


7. Write a program to display the first, last name, salary and department number for those
employees whose first name does not contain the letter ‘M’.

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},
]

for employee in employees:


first_name = employee["first_name"]
if 'M' not in first_name:
last_name = employee["last_name"]
salary = employee["salary"]
department_number = employee["department_number"]
print("First Name: {}, Last Name: {}, Salary: {}, Department Number: {}".format(first_name,
last_name, salary, department_number))

Output

Parv Jain Page | 34 09714004422

You might also like