Project File - 240430 - 140428
Project File - 240430 - 140428
Practical File
session 2024-25
5 - 8 LIST
9 - 13 TUPLE
14 - 18 DICTIONARY
19 - 22 CSV FILE
23 - 26 BINARY FILE
27 - 32 TEXT FILE
38 - 41 STACK
STRING
Answer :
s = input("Enter a string: ")
r = s[::-1]
if s == r:
print("The string is a
palindrome.")
else:
print("The string is not a
palindrome.")
Output
lst.sort()
prefix = lst[0]
for i in range(1, len(lst)):
while not lst[i].startswith(prefix):
prefix = prefix[:-1]
if prefix == "":
break
return prefix
lst = input("Enter a list of strings separated by
commas: ").split(",")
OUTPUT
ANSWER:
def title_case(s):
words = s.split()
new_words = []
skip_words = {"the", "of", "and", "or", "in", "a",
"an"}
new_words.append(word)
return " ".join(new_words)
OUTPUT
return password
length = int(input("Enter the length of the
password: "))
OUTPUT
LIST
QUESTION 1 Consider a list L=[1,2,3,4,5,2,4,2]
Write a user defined function SearchReplace()
that would access every element in the list and
replace those divisible by 2 by 0 and an
appropriate message is displayed is every
element is divisible by 2.
ANSWER:
L=[1,2,3,4,5,2,4,2]
n=2
def SearchReplace(L,n):
k=0
for i in range(len(L)):
if L[i]==n:
L[i]=0
else:
k=1
if k==0
print("Number not found")
print("The updated list is", L)
SearchReplace(L,n)
OUTPUT
ANSWER:
L=[1,2,3,4,5,6,7,8,9,10]
n=2
def SearchReplace(L,n):
k=0
for i in range(len(L)):
if L[i]%n==0:
L[i]=0
else:
k=1
if k==0:
print("Number not found")
print("The updated List is",L)
SearchReplace(L,n)
OUTPUT
OUTPUT
OUTPUT
ANSWER-
def odd_list(n):
odd_list = []
num = 1
for i in range(n):
odd_list.append(num)
num += 2
return odd_list
n = int(input("Enter the number of odd numbers:
"))
print("The list of odd numbers is:", odd_list(n))
OUTPUT
TUPLE
ANSWER-
t = (10, 20, 30, 40, 50)
print("The second element is:", t[1])
print("The fourth element is:", t[3])
OUTPUT
ANSWER-
t1 = (1, 2, 3)
t2 = (4, 5, 6)
print("The original tuples are:")
print("t1 =", t1)
print("t2 =", t2)
t3 = t1
t1 = t2
t2 = t3
print("The swapped tuples are:")
print("t1 =", t1)
print("t2 =", t2)
OUTPUT
ANSWER-
t = (1, 2, 3, 1, 4, 1)
e = int(input("Enter the element to be counted:
"))
c = t.count(e)
print("The element", e, "occurs", c, "times in the
tuple.")
OUTPUT
QUESTION 4 Sort a tuple of strings in alphabetical order. For
example, if the tuple is (“apple”, “banana”,
“cherry”), the output should be (“apple”,
“banana”, “cherry”).
ANSWER-
t = ("apple", "banana", "cherry")
print("The original tuple is:", t)
t = tuple(sorted(t))
print("The sorted tuple is:", t)
OUTPUT
ANSWER-
l = [1, 2, 3, 4, 5]
print("The original list is:", l)
t = tuple(l)
print("The converted tuple is:", t)
OUTPUT
DICTIONARY
QUESTION 1 Create a dictionary of students and their marks,
where the keys are the names of the students and
the values are their marks. Then, print the
dictionary and the average mark of the class.
ANSWER-
students = {"Alice": 85, "Bob": 90, "Charlie": 75,
"David": 80, "Eve": 95}
print("The dictionary of students and their marks
is:", students)
total = 0
for mark in students.values():
total += mark
average = total / len(students)
print("The average mark of the class is:",
average)
OUTPUT
OUTPUT
ANSWER-
countries = {"India": "New Delhi", "China":
"Beijing", "Japan": "Tokyo", "France": "Paris",
"Germany": "Berlin"}
country = input("Enter a country name: ")
if country in countries:
print("The capital of", country, "is:",
countries[country])
else:
print("Country not found")
OUTPUT
QUESTION 5 Create a dictionary of employees and their
salaries, where the keys are the names of the
employees and the values are their salaries. Then,
print the dictionary and the name of the
employee with the highest salary.
ANSWER-
employees = {"Alice": 5000, "Bob": 6000,
"Charlie": 4000, "David": 7000, "Eve": 8000}
print("The dictionary of employees and their
salaries is:", employees)
max_salary = 0
max_name = ""
for name, salary in employees.items():
if salary > max_salary:
max_salary = salary
max_name = name
print("The name of the employee with the highest
salary is:", max_name)
OUTPUT
CSV FILE
QUESTION 1 Write a program to read a CSV file named
“students.csv” that contains the names and marks
of five students in two columns, and print the
name and percentage of each student. Assume
that the total marks are 100. If the file content is:
Alice,85
Bob,90
Charlie,75
David,80
Eve,95
ANSWER-
import csv
f = open("students.csv", "r")
reader = csv.reader(f)
name = row[0]
mark = int(row[1])
percentage = mark / 100 * 100
print(name + ": " + str(percentage) + "%")
f.close()
OUTPUT
QUESTION 2 Write a CSV file named “products.csv” that
contains the names and prices of four products in
two columns, and then read the file and print the
total price of all the products. For example, if the
file content is:
Apple,0.99
Banana,0.79
Cherry,1.29
Orange,0.89
ANSWER-
import csv
f = open("products.csv", "w")
writer = csv.writer(f)
writer.writerow(["Apple", 0.99])
writer.writerow(["Banana", 0.79])
writer.writerow(["Cherry", 1.29])
writer.writerow(["Orange", 0.89])
f.close()
f = open("products.csv", "r")
reader = csv.reader(f)
total = 0
for row in reader:
price = float(row[1])
total += price
print("The total price is:", total)
f.close()
OUTPUT
QUESTION 3 Write a program to read a CSV file named
“countries.csv” that contains the names and
capitals of five countries in two columns, and then
ask the user to enter a country name and print its
capital if it exists in the file, or print “Country not
found” otherwise. For example, if the file content
is:
India,New Delhi
China,Beijing
Japan,Tokyo
France,Paris
Germany,Berlin
ANSWER-
import csv
f = open("countries.csv", "r")
reader = csv.reader(f)
countries = {}
for row in reader:
country = row[0]
capital = row[1]
countries[country] = capital
f.close()
country = input("Enter a country name: ")
if country in countries:
print("The capital of", country, "is:",
countries[country])
else:
print("Country not found")
OUTPUT
QUESTION 4 Write a program to read a CSV file named
“employees.csv” that contains the names,
departments, and salaries of five employees in
three columns, and then print the name and
department of the employee with the lowest
salary. For example, if the file content is:
Arun,IT,5000
Bimal,HR,6000
Charlie,Finance,4000
Danish,Marketing,7000
Esther,Sales,8000
ANSWER-
import csv
f = open("employees.csv", "r")
reader = csv.reader(f)
min_salary = float("inf")
min_name = ""
min_dept = ""
for row in reader:
name = row[0]
dept = row[1]
salary = float(row[2])
if salary < min_salary:
min_salary = salary
min_name = name
min_dept = dept
print("The employee with the lowest salary is:",
min_name)
print("The department of the employee with the
lowest salary is:", min_dept)
f.close()
OUTPUT
OUTPUT
BINARY FILE
QUESTION 1 Write a program to create a binary file named
“numbers.dat” that contains the numbers from 1
to 10 in binary format, and then read the file and
print the numbers in decimal format.
ANSWER-
import struct
f = open("numbers.dat", "wb")
for i in range(1, 11):
data = struct.pack('i', i)
f.write(data)
f.close()
f = open("numbers.dat", "rb")
while True:
data = f.read(4)
if not data:
break
num = struct.unpack('i', data)[0]
print(num)
f.close()
OUTPUT
QUESTION 2 Write a program to read a binary file named
“image.jpg” that contains an image in JPEG
format, and then write the file as
“image_copy.jpg” in the same format.
ANSWER-
f = open("image.jpg", "rb")
data = f.read()
f.close()
f = open("image_copy.jpg", "wb")
f.write(data)
f.close()
ANSWER-
import os
size = os.path.getsize("music.mp3")
OUTPUT
QUESTION 4 Write a program to create a binary file named
“students.dat” that contains the names and marks
of three students in two fields, and then read the
file and print the name and percentage of each
student. Assume that the total marks are 100.
ANSWER-
import pickle
f = open("students.dat", "wb")
students = [("Alice", 85), ("Bob", 90), ("Charlie",
75)]
pickle.dump(students, f)
f.close()
f = open("students.dat", "rb")
students = pickle.load(f)
f.close()
for name, mark in students:
percentage = mark / 100 * 100
print(name + ": " + str(percentage) + "%")
OUTPUT
f.close()
total = sum(numbers)
average = total / len(numbers)
print("The sum of the numbers is:", total)
print("The average of the numbers is:", average)
OUTPUT
TEXT FILE
QUESTION 1 Write a program to create a text file named
“hello.txt” that contains the word “Hello” in it,
and then read the file and print the word on the
screen.
ANSWER-
f = open("hello.txt", "w")
f.write("Hello")
f.close()
f = open("hello.txt", "r")
word = f.read()
print(word)
f.close()
OUTPUT
f.close()
chars = len(text)
words = len(text.split())
sentences = len(text.split("."))
print("The number of characters is:", chars)
print("The number of words is:", words)
print("The number of sentences is:", sentences)
OUTPUT
f.close()
f = open("table.txt", "r")
table = f.read()
print(table)
f.close()
OUTPUT
f.close()
names.sort()
for name in names:
print(name)
OUTPUT
OUTPUT
PYTHON SQL
CONNECTIVITY
QUESTION 1 Write a Python program to connect to a SQLite
database named “school.db” using the sqlite3
module and print the names of the tables in the
database.
ANSWER-
import sqlite3
conn = sqlite3.connect("school.db")
cursor = conn.cursor()
cursor.execute("SELECT name FROM
sqlite_master WHERE type='table'")
result = cursor.fetchall()
print("The names of the tables in the database
are:")
for row in result:
print(row[0])
cursor.close()
conn.close()
OUTPUT
conn.commit()
cursor.close()
conn.close()
ANSWER-
import sqlite3
conn = sqlite3.connect("school.db")
cursor = conn.cursor()
sql = "INSERT INTO courses (id, name,
teacher_id) VALUES (?, ?, ?)"
values = [
(1, 'Math', 101),
(2, 'English', 102),
(3, 'Science', 103)
]
cursor.executemany(sql, values)
conn.commit()
print(f"{cursor.rowcount} rows inserted")
cursor.close()
conn.close()
OUTPUT
ANSWER-
import sqlite3
conn = sqlite3.connect("school.db")
cursor = conn.cursor()
cursor.execute("SELECT * FROM courses")
result = cursor.fetchall()
print("id\tname\tteacher_id")
for row in result:
print(f"{row[0]}\t{row[1]}\t{row[2]}")
cursor.close()
conn.close()
OUTPUT
QUESTION 5 Write a Python program to update the name of
the course with id 2 to ‘Literature’ in the table
“courses” in the SQLite database “school.db”
using the execute() method of the cursor object.
cursor.close()
conn.close()
OUTPUT
STACK
QUESTION 1 Write a Python program to check if a given string
is a palindrome using a stack. A palindrome is a
word that is the same when read forward or
backward. For example, “madam” and “racecar”
are palindromes.
ANSWER-
def is_palindrome(string):
stack = []
for char in string:
stack.append(char)
for i in range(len(string)):
if string[i] != stack.pop():
return False
return True
print(is_palindrome("madam")) # True
print(is_palindrome("racecar")) # True
print(is_palindrome("python")) # False
OUTPUT
ANSWER-
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
s = Stack()
s.push(1)
s.push(2)
s.push(3)
print(s.peek()) # 3
print(s.pop()) # 3
print(s.size()) # 2
print(s.is_empty()) # False
OUTPUT
ANSWER-
def reverse_string(string):
stack = []
for char in string:
stack.append(char)
reversed_string = ""
while not len(stack) == 0:
reversed_string += stack.pop()
return reversed_string
print(reverse_string("hello")) # olleh
print(reverse_string("stack")) # kcats
OUTPUT
ANSWER-
def is_balanced(expression):
stack = []
for char in expression:
if char == "(":
stack.append(char)
elif char == ")":
if len(stack) == 0:
return False
if stack.pop() != "(":
return False
if len(stack) != 0:
return False
return True
print(is_balanced("(a+b)*(c-d)")) # True
OUTPUT
print(is_balanced("((a+b)+(c-d))")) # True
print(is_balanced("(a+b)*(c-d))")) # False
print(is_balanced("((a+b)+(c-d)")) # False