University Institute of Engineering and
Technology (Panjab University) , Chandigarh
Python Assignment
Submitted to : Mr. Sukhvir
Singh
Submitted by : Harsh
Barnwal
(UE218122)
B.E. IT 5th Semester
1. Write a python program for a shop to search a book using a unique number/code.
class BookShop:
def __init__(self):
# Initialize an empty dictionary to store book information
self.book_inventory = {}
def add_book(self, code, title, author, price):
# Add a book to the inventory
self.book_inventory[code] = {'title': title, 'author': author, 'price': price}
def search_book(self, code):
# Search for a book using the unique code
book_details = self.book_inventory.get(code)
if book_details:
print(f"Book found!\nTitle: {book_details['title']}\nAuthor:
{book_details['author']}\nPrice: {book_details['price']}")
else:
print("Book not found.")
# Example usage:
if __name__ == "__main__":
# Create a BookShop instance
book_shop = BookShop()
# Add some books to the inventory
book_shop.add_book('101', 'Python', 'Harsh Barnwal', 300)
book_shop.add_book('102', 'Network Security', 'Harper Lee', 149)
book_shop.add_book('103', 'Artificial Intelligence', 'George Orwell', 999)
# Search for a book using a code
search_code = input("Enter the book code to search: ")
book_shop.search_book(search_code)
OUTPUT:
2. Write a program using python to:
i. open a file having list of names (min five names).
ii. open a file having content of the mail (a paragraph).
iii. read all the content of the body of the email (paragraph).
iv. iterate over list of names and merge with content of the mail (Hello + Namei + Content).
v. write the mails to individual files.
# Assuming you have two files: names.txt and email_content.txt
def merge_and_write_emails(names_file_path, email_content_file_path, output_directory):
# Read names from the file
with open(names_file_path, 'r') as names_file:
names = [name.strip() for name in names_file.readlines()]
# Read the content of the email
with open(email_content_file_path, 'r') as email_content_file:
email_content = email_content_file.read()
# Create emails and write to individual files
for i, name in enumerate(names, start=1):
# Construct the email content
merged_email_content = f"Hello {name},\n\n{email_content}"
# Write the email to an individual file
output_file_path = f"{output_directory}/email_{i}.txt"
with open(output_file_path, 'w') as output_file:
output_file.write(merged_email_content)
print(f"Email for {name} written to {output_file_path}")
# Example usage:
names_file_path = '/content/sample_data/names.txt'
email_content_file_path = '/content/sample_data/email_contents.txt'
output_directory = 'outputharsh'
# Ensure the output directory exists
import os
os.makedirs(output_directory, exist_ok=True)
merge_and_write_emails(names_file_path, email_content_file_path, output_directory)
OUTPUT:
3. What is the significance of super() method in python programing. Use suitable example.
class Parent:
def __init__(self, name):
self.name = name
class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # Calls the __init__ method of the parent class
self.age = age
# Example usage
child_instance = Child("Harsh Barnwal", 21)
print(f"Name: {child_instance.name}, Age: {child_instance.age}")
OUTPUT:
4. i) Create a table-Employee, database-Company having following columns:
Name, Age, Designation and Salary
ii) Insert five rows into the table-Employee.
iii) Find and display the row(s) having your name in it.
import sqlite3
# Connect to the database
connection = sqlite3.connect("Company.db")
cursor = connection.cursor()
# Create the Employee table
cursor.execute('''
CREATE TABLE IF NOT EXISTS Employee (
Name TEXT,
Age INTEGER,
Designation TEXT,
Salary REAL
)
''')
# Insert five rows into the Employee table
data = [
("Ajit", 30, "Manager", 70000),
("Yash", 24, "Developer", 60000),
("Timir", 31, "Analyst", 80000),
("Sorav", 25, "Intern", 40000),
("Harsh Barnwal", 36, "Engineer", 900000)
]
cursor.executemany('''
INSERT INTO Employee (Name, Age, Designation, Salary) VALUES (?, ?, ?, ?)
''', data)
# Commit the changes
connection.commit()
# Find and display the row(s) having your name
cursor.execute('SELECT * FROM Employee WHERE Name = "Harsh Barnwal"')
rows = cursor.fetchall()
print("Rows with YourName:")
for row in rows:
print(row)
# Close the connection
connection.close()
OUTPUT:
5. i) Create a program to design a GUI window with two textboxes and one button.
ii) Fetch the rows from the table-Employee created in Q no. 3 where Age >25 and Salary > 300000.
(Enter age and salary in the textboxes and fetch the rows on clicking the button.)
import tkinter as tk
from tkinter import messagebox
import sqlite3
def fetch_data():
age = int(age_entry.get())
salary = float(salary_entry.get())
# Connect to the database
connection = sqlite3.connect("Company.db")
cursor = connection.cursor()
# Fetch rows where Age > 25 and Salary > 300000
cursor.execute('''
SELECT * FROM Employee WHERE Age > ? AND Salary > ?
''', (age, salary))
rows = cursor.fetchall()
# Display the fetched rows
result_text.delete(1.0, tk.END) # Clear previous content
for row in rows:
result_text.insert(tk.END, f"{row}\n")
# Close the connection
connection.close()
# Create GUI window
window = tk.Tk()
window.title("Employee Data Fetcher")
# Create textboxes
age_label = tk.Label(window, text="Enter Age:")
age_label.pack()
age_entry = tk.Entry(window)
age_entry.pack()
salary_label = tk.Label(window, text="Enter Salary:")
salary_label.pack()
salary_entry = tk.Entry(window)
salary_entry.pack()
# Create button
fetch_button = tk.Button(window, text="Fetch Data", command=fetch_data)
fetch_button.pack()
# Create textbox for displaying results
result_text = tk.Text(window, height=10, width=50)
result_text.pack()
# Run the GUI
window.mainloop()
OUTPUT: