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

Combined_Library_Management_and_Exercises

The document contains a series of programming questions and answers covering various topics such as data structures, classes, GUI applications, and file handling in Python. Each question includes code snippets demonstrating specific functionalities like calculating maximum/minimum values, checking for duplicates, and implementing a simple library management system. Additionally, it showcases the use of libraries like tkinter for GUI and pandas for data manipulation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Combined_Library_Management_and_Exercises

The document contains a series of programming questions and answers covering various topics such as data structures, classes, GUI applications, and file handling in Python. Each question includes code snippets demonstrating specific functionalities like calculating maximum/minimum values, checking for duplicates, and implementing a simple library management system. Additionally, it showcases the use of libraries like tkinter for GUI and pandas for data manipulation.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

Question 1

Question 2
# Question 10: Max and Min from a set
nums = {4, 7, 1, 9, 3}
print("Maximum:", max(nums))
print("Minimum:", min(nums))
Question 3
# Question 11: Check for duplicates in a list
my_list = [1, 2, 3, 4, 2, 5]
if len(my_list) != len(set(my_list)):
print("List has duplicates")
else:
print("List has no duplicates")
Question 4
# Question 12: Class to store employee data
class Employee:
def __init__(self, name, year, salary, address):
self.name = name
self.year = year
self.salary = salary
self.address = address

def display(self):
print(f"{self.name}, {self.year}, {self.salary}, {self.address}")

e1 = Employee("Alice", 2010, 30000, "City A")


e2 = Employee("Bob", 2015, 40000, "City B")
e3 = Employee("Charlie", 2020, 50000, "City C")

e1.display()
e2.display()
e3.display()
Question 5
# Question 13: Rectangle class with area and perimeter
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width

def area(self):
return self.length * self.width

def perimeter(self):
return 2 * (self.length + self.width)

l = float(input("Enter length: "))


w = float(input("Enter width: "))
rect = Rectangle(l, w)
print("Area:", rect.area())
print("Perimeter:", rect.perimeter())
Question 6
# Question 14: Count word frequency in file and save to another file
with open("input.txt", "r") as file:
text = file.read()

words = text.split()
freq = {}

for word in words:


word = word.lower().strip(".,")
freq[word] = freq.get(word, 0) + 1

with open("output.txt", "w") as file:


for word, count in freq.items():
file.write(f"{word}: {count}\n")
Question 7
# Question 15: GUI for circle area calculation
import tkinter as tk
from math import pi

def calculate_area():
r = float(entry.get())
area = pi * r * r
result.config(text=f"Area: {area:.2f}")

win = tk.Tk()
tk.Label(win, text="Enter radius:").pack()
entry = tk.Entry(win)
entry.pack()
tk.Button(win, text="Calculate", command=calculate_area).pack()
result = tk.Label(win)
result.pack()
win.mainloop()
Question 8
# Question 16: GUI to input personal info and display it styled
import tkinter as tk

def show_info():
info = f"{name.get()}, {street.get()}, {city.get()}, {pincode.get()}"
output.config(text=info, font=("Arial", 32, "italic"))

win = tk.Tk()
win.title("MyInfo")

tk.Label(win, text="Name").pack()
name = tk.Entry(win)
name.pack()

tk.Label(win, text="Street").pack()
street = tk.Entry(win)
street.pack()

tk.Label(win, text="City").pack()
city = tk.Entry(win)
city.pack()

tk.Label(win, text="Pincode").pack()
pincode = tk.Entry(win)
pincode.pack()

tk.Button(win, text="MyInfo", command=show_info).pack()


output = tk.Label(win)
output.pack()

win.mainloop()
Question 9
# Question 17: Simple Library Management System
library = []

def issue_book(book):
if book not in library:
library.append(book)
print(f"{book} issued.")
else:
print(f"{book} already issued.")

def return_book(book):
if book in library:
library.remove(book)
print(f"{book} returned.")
else:
print(f"{book} was not issued.")

def view_books():
print("Issued books:", library)

issue_book("Python Basics")
issue_book("ML Guide")
view_books()
return_book("Python Basics")
view_books()
Question 10
# Question 18: String operations
s1 = input("Enter string 1: ")
s2 = input("Enter string 2: ")

print("0th character:", s1[0])


print("3rd to 6th character:", s1[3:7])
print("6th character onwards:", s1[6:])
print("Last character:", s1[-1])
print("String twice:", s1 * 2)
print("Concatenated string:", s1 + s2)
Question 11
# Question 19: Find longest word
sentence = input("Enter a sentence: ")
words = sentence.split()
longest = max(words, key=len)
print("Longest word:", longest)
Question 12
# Question 20: Remove duplicates from list
def get_unique(lst):
return list(set(lst))

nums = [1, 2, 2, 3, 4, 4, 5]
print("Unique elements:", get_unique(nums))
Question 13
# Question 21: Filter even and odd using lambda
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

even = list(filter(lambda x: x % 2 == 0, nums))


odd = list(filter(lambda x: x % 2 != 0, nums))

print("Even numbers:", even)


print("Odd numbers:", odd)
Question 14
# Question 22: 2D array using numpy
import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])


print("Original Array:\n", arr)

print("Sliced (row 0):", arr[0])


reshaped = arr.reshape(3, 2)
print("Reshaped (3x2):\n", reshaped)

print("Shape:", arr.shape)
print("Size:", arr.size)
Question 15
# Question 23: Check if string starts with given char using lambda
check = lambda s, c: s.startswith(c)

string = input("Enter a string: ")


char = input("Enter the character: ")

if check(string, char):
print("Yes, string starts with", char)
else:
print("No, it doesn't start with", char)
Question 16
# Question 24: Dictionary from string with letter frequency
s = 'vcetresource'
freq = {}

for ch in s:
if ch in freq:
freq[ch] += 1
else:
freq[ch] = 1

print(freq)
Question 17
# Question 25: Find max and min in a set
nums = {11, 4, 22, 7, 3}
print("Maximum:", max(nums))
print("Minimum:", min(nums))
Question 18
# Question 26: Check if sets have no elements in common
set1 = {1, 2, 3}
set2 = {4, 5, 6}

if set1.isdisjoint(set2):
print("No elements in common")
else:
print("Sets have common elements")
Question 19
# Question 27: Remove duplicates from a list
lst = [1, 2, 2, 3, 4, 4, 5]
unique_lst = list(set(lst))
print("List without duplicates:", unique_lst)
Question 20
# Question 28: Separate even and odd numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
even = []
odd = []

for num in numbers:


if num % 2 == 0:
even.append(num)
else:
odd.append(num)

print("Even numbers:", even)


print("Odd numbers:", odd)
Question 21
# Question 29: Find second largest number
lst = [10, 20, 4, 45, 99]
lst.sort()
print("Second largest:", lst[-2])
Question 22
# Question 3: Simple calculator with exception handling
try:
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Choose operation (+, -, *, /):")
op = input("Enter operation: ")

if op == '+':
print("Result:", a + b)
elif op == '-':
print("Result:", a - b)
elif op == '*':
print("Result:", a * b)
elif op == '/':
print("Result:", a / b)
else:
print("Invalid operator")
except ValueError:
print("Invalid input! Please enter numbers.")
except ZeroDivisionError:
print("Cannot divide by zero.")
Question 23
# Question 30: Calculate electricity bill
def calc_bill(units):
if units <= 100:
return 0
elif units <= 200:
return (units - 100) * 5
else:
return (100 * 5) + (units - 200) * 10

for i in range(5):
u = int(input(f"Enter units for user {i+1}: "))
print(f"Total bill: Rs.{calc_bill(u)}")
Question 24
# Question 31: Various operations on a string
string = '''Ants are found everywhere in the world. They make their home in
buildings, gardens etc. They live in anthills. Ants are very hardworking insects.
Throughout the summers they collect food for the winter season. Whenever
they find a sweet lying on the floor they stick to the sweet and carry it to their
home. Thus, in this way, they clean the floor. Ants are generally red and black
in colour. They have two eyes and six legs. They are social insects. They live
in groups or colonies. Most ants are scavengers they collect whatever food
they can find. They are usually wingless but they develop wings when they
reproduce. Their bites are quite painful.'''

words = string.split()

# a. Words starting with s


s_start = [w for w in words if w.startswith('s')]
print("Words starting with 's':", s_start)

# b. Words starting and ending with s


s_start_end = [w for w in words if w.startswith('s') and w.endswith('s')]
print("Words starting and ending with 's':", s_start_end)

# c. Words containing i
contains_i = [w for w in words if 'i' in w]
print("Words containing 'i':", contains_i)

# d. Capitalize first letter of every word


capitalized = string.title()
print("Capitalized String:\n", capitalized)

# e. Word frequency dictionary


freq = {}
for word in words:
word = word.lower().strip(".,")
freq[word] = freq.get(word, 0) + 1
print("Word frequency:\n", freq)
Question 25
# Question 32: Custom module example

# Save this part in a file named mymodule.py:


# def greet(name):
# print("Hello", name)

# Main program:
import mymodule
mymodule.greet("Student")
Question 26
# Question 33: Matrix addition using nested lists
a = [[1, 2], [3, 4]]
b = [[5, 6], [7, 8]]
result = [[0, 0], [0, 0]]

for i in range(2):
for j in range(2):
result[i][j] = a[i][j] + b[i][j]

print("Sum of matrices:")
for row in result:
print(row)
Question 27
# Question 34: Different types of plots
import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y = [2, 4, 1, 6, 7]

plt.subplot(1, 3, 1)
plt.plot(x, y)
plt.title("Line Plot")

plt.subplot(1, 3, 2)
plt.bar(x, y)
plt.title("Bar Plot")

plt.subplot(1, 3, 3)
plt.scatter(x, y)
plt.title("Scatter Plot")

plt.tight_layout()
plt.show()
Question 28
# Question 35: Basic data manipulation with pandas
import pandas as pd

data = {
"Name": ["A", "B", "C"],
"Marks": [85, 90, 95]
}

df = pd.DataFrame(data)
print("Original Data:\n", df)

print("Average Marks:", df["Marks"].mean())


Question 29
# Question 36: Sort dictionary by value
my_dict = {'a': 5, 'b': 2, 'c': 9, 'd': 1}

# Ascending
asc = dict(sorted(my_dict.items(), key=lambda x: x[1]))
print("Ascending:", asc)

# Descending
desc = dict(sorted(my_dict.items(), key=lambda x: x[1], reverse=True))
print("Descending:", desc)
Question 30
# Question 37: Get top 3 most expensive items
shop = {'item1': 45.50, 'item2': 35, 'item3': 41.30, 'item4': 55, 'item5': 24}
top_items = sorted(shop.items(), key=lambda x: x[1], reverse=True)[:3]

for item, price in top_items:


print(item, price)
Question 31
# Question 38: Library System using dictionary
library = {}

def add_book(book):
library[book] = "Available"

def issue_book(book):
if book in library and library[book] == "Available":
library[book] = "Issued"
print(f"{book} has been issued.")
else:
print(f"{book} is not available.")

def return_book(book):
if book in library and library[book] == "Issued":
library[book] = "Available"
print(f"{book} has been returned.")

def view_books():
print("Library Books:")
for book, status in library.items():
print(f"{book} - {status}")

# Sample usage
add_book("Python 101")
add_book("AI Basics")
view_books()
issue_book("Python 101")
view_books()
return_book("Python 101")
view_books()
Question 32
# Question 4: Calculate area and perimeter of a rectangle
def area(length, breadth):
return length * breadth

def perimeter(length, breadth):


return 2 * (length + breadth)

l = float(input("Enter length: "))


b = float(input("Enter breadth: "))

print("Area:", area(l, b))


print("Perimeter:", perimeter(l, b))
Question 33
# Question 5: Simple GUI to input and display a record
import tkinter as tk

def display():
name = entry.get()
output.config(text="Record: " + name)

win = tk.Tk()
win.title("Simple GUI")

tk.Label(win, text="Enter your name:").pack()


entry = tk.Entry(win)
entry.pack()

tk.Button(win, text="Display", command=display).pack()


output = tk.Label(win, text="")
output.pack()

win.mainloop()
Question 34
# Question 6: Store marks and calculate total and percentage
marks = []
for i in range(5):
mark = float(input(f"Enter marks for subject {i+1}: "))
marks.append(mark)

total = sum(marks)
percentage = total / 5

print("Total Marks:", total)


print("Percentage:", percentage)
Question 35
# Question 7: Class with setDim and getArea
class Area:
def setDim(self, length, breadth):
self.length = length
self.breadth = breadth

def getArea(self):
return self.length * self.breadth

a = Area()
l = float(input("Enter length: "))
b = float(input("Enter breadth: "))
a.setDim(l, b)
print("Area of Rectangle:", a.getArea())
Question 36
# Question 8: Map two lists to dictionary
colors = ["red", "blue"]
hex_codes = ["#ff0000", "#00ff00"]

color_dict = dict(zip(colors, hex_codes))


print(color_dict)
Question 37
# Question 9: Check element in tuple
my_tuple = (1, 3, 5, 7, 9)
elem = int(input("Enter element to search: "))

if elem in my_tuple:
print("Element exists in tuple")
else:
print("Element does not exist")
Question 38
cost_price = float(input("Enter the cost price of the bike: "))

if cost_price > 100000:


tax = cost_price * 0.15
elif cost_price > 50000:
tax = cost_price * 0.10
else:
tax = cost_price * 0.05

final_amount = cost_price + tax


print("Tax to be paid:", tax)
print("Final amount of bike:", final_amount)
Question 39
# Question 2: Square and cube numbers using lambda
numbers = [1, 2, 3, 4, 5]

squares = list(map(lambda x: x ** 2, numbers))


cubes = list(map(lambda x: x ** 3, numbers))

print("Original list:", numbers)


print("Squares:", squares)
print("Cubes:", cubes)

You might also like