Practical File 2024-25
Practical File 2024-25
Practical File
session 2024-25
S T Te r e s a S c h o o l
Submitted to: Mrs Vinita Sharma
Shakti Khand-II, (HOD Cs)
Indirapuram Ghaziabad- Submitted by: Aneek Chatterjee
201014 (U.P) India
INDEX
1 - 4 STRING
5 - 9 LIST
10 - 12 TUPLE
13 - 16 D I C T I O N A RY
17 - 21 C S V FILE
22 - 27 B I N A RY FILE
28 - 34 TEXT FILE
35 - 38 PYTHON S Q L CONNECTIVITY
39 - 43 S TA C K
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
L IS T
QUESTION Consider a list L=[1,2,3,4,5,2,4,2]
1 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)
O UTPUT
A N S W ER
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)
O UTPUT SearchReplace(L,n)
O UTPUT
O UTPUT
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))
O UTPUT
T U PL E
A N S W ER -
t = (10, 20, 30, 40, 50)
print("The second element is:", t[1])
print("The fourth element is:", t[3])
O UTPUT
A N S W ER -
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)
O UTPUT
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)
O UTPUT
A N S W ER -
l = [1, 2, 3, 4, 5]
print("The original list is:", l)
t = tuple(l)
print("The converted tuple
is:", t)
O UTPUT
D I C T I O NA RY
QUESTION Create a dictionary of students and their marks,
1 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.
A N S W ER -
students = {"Alice": 85, "Bob": 90, "Charlie": 75,
"Dav id": 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)
O UTPUT
O UTPUT
A N S W ER -
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.
A N S W ER -
employees = {"Alice": 5000, "Bob": 6000,
"Charlie": 4000, "Dav id": 7000, "Eve": 8 0 0 0 }
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)
O UTPUT
CSV FILE
QUESTION Write a program to read a C S V file named
1 “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
C harlie,7
5
David,80
Eve,95
A N S W ER -
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()
O UTPUT
Q U E S T I O N 2 Write a C S V 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
O rang e,0 .8
9
A N S W ER -
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()
O UTPUT
QUESTION 3 Write a program to read a C S V 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
A N S W ER -
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")
O UTPUT
QUESTION 4 Write a program to read a C S V 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
A N S W ER -
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()
O UTPUT
ANSWER-
import struct
f = open("numbers.dat", " w b " )
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.
A N S W ER -
f = open("image.jpg", "rb")
data = f.read()
f.close()
f.close()
A N S W ER -
import os
size = os.path.getsize("music.mp3")
O UTPUT
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", " w b " )
students = [("Alice", 85), ("Bob", 90), ("Charlie", 75)]
pickle.dump(students, f)
f.close()
O UTPUT
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)
O UTPUT
def writetob():
with open('students.pickle', 'wb') as binary_file:
name = input('Enter Name')
roll_number = int(input('Enter roll number'))
student = [name, roll_number]
pickle.dump(student, binary_file)
def Search(roll_number):
try:
with open('students.pickle', 'rb') as binary_file:
while True:
try:
student = pickle.load(binary_file)
if student[1] == roll_number:
print("Name:", student[0])
return
except EOFError:
print("Roll number not found.")
break
except:
print('An Error occurred')
writetob()
roll_no = 30
Search(roll_no)
O UTPUT
ANSWER-
import pickle
def writetob():
with open('students.pickle', 'ab') as binary_file:
roll_number = int(input('Enter roll number: '))
name = input('Enter Name: ')
marks = int(input('Enter marks: '))
student = {'roll_number': roll_number, 'name':
name, 'marks': marks}
pickle.dump(student, binary_file)
writetob()
roll_no = 30
new_marks = 90
Search(roll_no, new_marks)
O UTPUT
T E X T FILE
Q U E S T I O N 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.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)
O UTPUT
A N S W ER -
file = open("data.txt", "r")
line = file.readline()
values = line.split(" ")
for value in values:
print(value)
file.close()
O UTPUT
Q U E S T I O N 6 Read a text file line by line and display each word
separated by a #.
A N S W ER - def process_file():
try:
with open('data.txt', 'r') as file:
for line in file:
words = line.split()
formatted_line = '#'.join(words)
print(formatted_line)
except FileNotFoundError:
print("File not found.")
process_file()
O UTPUT
vowels/consonants/uppercase/lowercase
A N S W ER - def count_characters():
characters in the file.
vowels = "aeiouAEIOU"
consonants =
"bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTV
WXYZ"
uppercase_count = 0
lowercase_count = 0
vowel_count = 0
consonant_count = 0
try:
with open('data.txt', 'r') as file:
content = file.read()
for char in content:
if char.isalpha():
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
if char in vowels:
vowel_count += 1
elif char in consonants:
consonant_count += 1
print(f"Uppercase characters:
{uppercase_count}")
print(f"Lowercase characters:
{lowercase_count}")
print(f"Vowels: {vowel_count}")
print(f"Consonants: {consonant_count}")
except FileNotFoundError:
print("File not found.")
count_characters()
O UTPUT
Q U E S T I O N 6 Read all the lines that contain the character 'a' in a
remove_lines_with_a()
O UTPUT
PYTHON SQL
C O N N E C T IV IT Y
Q U E S T I O N 1 Write a Python program to connect to a
SQLdatabase named “school.db” using the
sqlite3 module and print the names of the
tables in the database.
ANSWER-
import mysql.connector as m
con = m.connect("school.db") cursor =
con.cursor()
cursor.execute("SELECT name F R O M
sqlite_master W H E R E type='table'")
result = cursor.fetchall()
print("The names of the tables in the database are:")
for row in result:
print(row[0])
cursor.close()
con.close()
OUTPUT
con.commit()
cursor.close(
) con.close()
cursor.close(
) con.close()
OUTPUT
O UTPUT
QUESTION 5 Write a Python program to update the name of
the course with id 2 to ‘Literature’ in the table
“courses” in the SQL database “school.db”
using the execute() method of the cursor object.
A N S W ER - import mysql.connector as m
con = m.connect("school.db")
cursor = conn.cursor()
sql = " U P D AT E courses SET name
= ? W H E R E id =
?
values = ('Literature', 2)
cursor.execute(sql, values)
con.commit() print(f"{cursor.rowcount}
row updated")
cursor.close(
) con.close()
OUTPUT
STAC K
Q U E S T I O N 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.
A N S W ER -
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
O UTPUT
OUTPUT
print(reverse_string("hello")) # olleh
print(reverse_string("stack")) #
kcats
OUTPUT