0% found this document useful (0 votes)
29 views42 pages

Project File - 240430 - 140428

Uploaded by

ironhero109
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views42 pages

Project File - 240430 - 140428

Uploaded by

ironhero109
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Computer Science (083)

Practical File
session 2024-25

Submitted to: Mrs Vinita Sharma


(HOD Cs)
certificate of completion

This is to certify that Jyotirmay Singh of


Class XI A1 , Board roll no. 11115 has
successfully completed his CS Project file
under the guidance of Ms. Vinita Sharma
(HoD CS ) for the academic session 2023-
2024.

Internal Examiner External Examiner


Name Name
Number Number
Signature Signature
INDEX
1 - 4 STRING

5 - 8 LIST

9 - 13 TUPLE

14 - 18 DICTIONARY

19 - 22 CSV FILE

23 - 26 BINARY FILE

27 - 32 TEXT FILE

33 - 37 PYTHON SQL CONNECTIVITY

38 - 41 STACK
STRING

Write a program to check if a given string is a


Question 1 palindrome or not. A palindrome is a word that is
the same when read backwards. For example,
“madam” is a palindrome, but “python” is not.

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

Question 2 Write a program to find the longest common


prefix of a list of strings. For example, if the list is
[“flower”, “flow”, “flight”], the output should be
“fl”.
Answer :
def longest_common_prefix(lst):
# If the list is empty, return an
empty stringif not lst:
return ""# If the list has only
one element, return that elementif
len(lst) == 1:
return lst[0]

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

print("The longest common prefix is:",


longest_common_prefix(lst))

OUTPUT

QUESTION 3 Write a program to convert a given string to title


case. Title case means that the first letter of each
word is capitalized, except for articles,
conjunctions, and prepositions.
For example, if the string is “the lord of the
rings”, the output should be “The Lord of the
Rings”.

ANSWER:

def title_case(s):
words = s.split()
new_words = []
skip_words = {"the", "of", "and", "or", "in", "a",
"an"}

for word in words:


if word.lower() not in skip_words:
word = word[0].upper() + word[1:]

new_words.append(word)
return " ".join(new_words)

s = input("Enter a string: ")


print("The title case string is:", title_case(s))

OUTPUT

QUESTION 4 Write a program to generate a random password


of a given length, using lowercase letters,
uppercase letters, digits, and symbols. For
example, if the length is 8, the output could be
“aB3!d@f”.
ANSWER:
import random
def random_password(length):
chars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKL
MNOPQRSTUVWXYZ0123456789!@#$%^&*"
password = ""
for i in range(length):
password += random.choice(chars)

return password
length = int(input("Enter the length of the
password: "))

print("The random password is:",


random_password(length))

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

QUESTION 2 Consider a list L=[1,2,3,4,5,6,7,8,9,10] and that K


is equal to 2 write a python program to replace
the number divisible by 2 by 0 if every elements
is divisible by 2 an appropriate message should
be displayed

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

QUESTION 3 Create a list of n prime numbers, where n is


entered by the user. A prime number is a natural
number that has exactly two factors: 1 and itself.
For example, the first 10 prime numbers are: 2, 3,
5, 7, 11, 13, 17, 19, 23, 29.
ANSWER- def is_prime(n):
if n < 2:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def prime_list(n):
prime_list = []
count = 0
num = 2
while count < n:
if is_prime(num):
prime_list.append(num)
count += 1
num += 1
return prime_list
n = int(input("Enter the number of prime
numbers: "))
print("The list of prime numbers is:",
prime_list(n))

OUTPUT

QUESTION 4 Create a list of n even numbers, where n is


entered by the user. An even number is a natural
number that is divisible by 2. For example, the
first 10 even numbers are: 2, 4, 6, 8, 10, 12, 14, 16,
18, 20.
ANSWER-
def even_list(n):
even_list = []
num = 2
for i in range(n):
even_list.append(num)
num += 2
return even_list

n = int(input("Enter the number of even numbers:


"))

print("The list of even numbers is:", even_list(n))

OUTPUT

QUESTION 5 Create a list of n odd numbers, where n is entered


by the user. An odd number is a natural number
that is not divisible by 2. For example, the first 10
odd numbers are: 1, 3, 5, 7, 9, 11, 13, 15, 17, 19.

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

QUESTION 1 Create a tuple of 5 elements and print the second


and fourth elements of the tuple.

ANSWER-
t = (10, 20, 30, 40, 50)
print("The second element is:", t[1])
print("The fourth element is:", t[3])

OUTPUT

QUESTION 2 Swap the values of two tuples using a third tuple.


For example, if the tuples are (1, 2, 3) and (4, 5,
6), the output should be (4, 5, 6) and (1, 2, 3).

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

QUESTION 3 Count the number of occurrences of a given


element in a tuple. For example, if the tuple is (1,
2, 3, 1, 4, 1) and the element is 1, the output should
be 3.

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

QUESTION 5 Convert a list of numbers into a tuple of numbers.


For example, if the list is [1, 2, 3, 4, 5], the output
should be (1, 2, 3, 4, 5).

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

QUESTION 2 Create a dictionary of words and their meanings,


where the keys are the words and the values are
their meanings. Then, ask the user to enter a word
and print its meaning if it exists in the dictionary,
or print “Word not found” otherwise.
words = {"python": "a high-level programming
ANSWER-
language", "bing": "a web search engine",
"tuple": "an immutable sequence of values in
Python"}
word = input("Enter a word: ")
if word in words:
print("The meaning of", word, "is:",
words[word])
else:
print("Word not found")

OUTPUT

QUESTION 3 Create a dictionary of products and their prices,


where the keys are the names of the products and
the values are their prices. Then, ask the user to
enter a product name and print its price if it exists
in the dictionary, or print “Product not found”
otherwise.

ANSWER- products = {"apple": 0.99, "banana": 0.79,


"cherry": 1.29, "orange": 0.89, "pear": 1.09}
product = input("Enter a product name: ")
if product in products:
print("The price of", product, "is:",
products[product])
else:
print("Product not found")
OUTPUT

QUESTION 4 Create a dictionary of countries and their capitals,


where the keys are the names of the countries
and the values are their capitals. Then, ask the
user to enter a country name and print its capital
if it exists in the dictionary, or print “Country not
found” otherwise.

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

QUESTION 5 Write a program to write a CSV file named


“fruits.csv” that contains the names and colors of
four fruits in two columns, and then read the file
and print the name of the fruit that has the color
“red”. For example, if the file content is:
Apple,red
Banana,yellow
Cherry,red
Orange,orange
ANSWER-
import csv
f = open("fruits.csv", "w")
writer = csv.writer(f)
writer.writerow(["Apple", "red"])
writer.writerow(["Banana", "yellow"])
writer.writerow(["Cherry", "red"])
writer.writerow(["Orange", "orange"])
f.close()
f = open("fruits.csv", "r")
reader = csv.reader(f)
for row in reader:
name = row[0]
color = row[1]
if color == "red":
print("The fruit that has the color red is:",
name)
f.close()

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

OUTPUT A copy of the original image.

QUESTION 3 Write a program to read a binary file named


“music.mp3” that contains an audio in MP3
format, and then print the size of the file in bytes.

ANSWER-
import os
size = os.path.getsize("music.mp3")

print("The size of the file is:", size, "bytes")

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

QUESTION 5 Write a program to read a binary file named


“data.dat” that contains a list of numbers in
binary format, and then print the sum and
average of the numbers. For example, if the file
content is:
[1, 2, 3, 4, 5]
ANSWER-
import pickle
f = open("data.dat", "rb")
numbers = pickle.load(f)

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

QUESTION 2 Write a program to read a text file named


“story.txt” that contains a story in it, and then
print the number of characters, words, and
sentences in the file. For example, if the file
content is:
Once upon a time, there was a king who had three
sons. The king was old and wanted to choose one
of his sons as his successor. He decided to test
their wisdom and courage by giving them a task.
He asked each of his sons to bring him the most
beautiful thing they could find in the world.
ANSWER- f = open("story.txt", "r")
text = f.read()

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

QUESTION 3 Write a program to write a text file named


“table.txt” that contains the multiplication table
of a number entered by the user, and then read
the file and print the table on the screen. For
example, if the user enters 5, the file content
should be:
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
ANSWER- n = int(input("Enter a number: "))
f = open("table.txt", "w")
for i in range(1, 11):
product = n * i
f.write(str(n) + " x " + str(i) + " = " +
str(product) + "\n")

f.close()

f = open("table.txt", "r")
table = f.read()
print(table)

f.close()

OUTPUT

QUESTION 4 Write a program to read a text file named


“names.txt” that contains the names of five
people in each line, and then print the names in
alphabetical order. For example, if the file
content is:
Alice,Bob,Charlie,David,Eve
Frank,Grace,Henry,Irene,Jack
Karen,Liam,Mia,Noah,Olivia
ANSWER- f = open("names.txt", "r")
names = []
for line in f:
names.extend(line.strip().split(","))

f.close()

names.sort()
for name in names:
print(name)

OUTPUT

QUESTION 5 Write a Python program to read a text file named


“data.csv” that contains comma-separated values
and print each value in a new line. Assume that
the file has a single line of values.
ANSWER-
file = open("data.csv", "r")
line = file.readline()
values = line.split(",")
for value in values:
print(value)
file.close()

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

QUESTION 2 Write a Python program to create a table named


“courses” in the SQLite database “school.db”
with the following columns: id (integer, primary
key), name (text), and teacher_id (integer,
foreign key referencing teachers.id).
ANSWER-
import sqlite3
conn = sqlite3.connect("school.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE courses (id
INTEGER PRIMARY KEY, name TEXT, teacher_id
INTEGER, FOREIGN KEY (teacher_id)
REFERENCES teachers (id))")

conn.commit()

cursor.close()
conn.close()

No output on the screen, but the table “courses”


OUTPUT
will be created in the database.

QUESTION 3 Write a Python program to insert three records


into the table “courses” in the SQLite database
“school.db” using the executemany() method of
the cursor object. The records are: (1, ‘Math’, 101),
(2, ‘English’, 102), and (3, ‘Science’, 103).

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

QUESTION 4 Write a Python program to fetch and display all


the records from the table “courses” in the SQLite
database “school.db” using the fetchall() method
of the cursor object.

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.

ANSWER- import sqlite3


conn = sqlite3.connect("school.db")
cursor = conn.cursor()
sql = "UPDATE courses SET name = ? WHERE id =
?
values = ('Literature', 2)
cursor.execute(sql, values)
conn.commit()
print(f"{cursor.rowcount} row updated")

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

QUESTION 2 Write a Python program to implement a stack


using a list. The stack should have the following
methods: push(item), pop(), peek(), is_empty(),
and size().

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

QUESTION 3 Write a Python program to reverse a string using


a stack.

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

QUESTION 4 Write a Python program to check if a given


expression has balanced parentheses using a
stack. Balanced parentheses mean that every
opening parenthesis has a matching closing
parenthesis and vice versa. For example, “(a+b)
(c-d)" and “((a+b)+(c-d))” are balanced, but "
(a+b)(c-d))” and “((a+b)+(c-d)” are not.

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

QUESTION 5 Write a Python program to print the elements of a


stack in reverse order using another stack. You
can use the following steps to print the stack in
reverse order:
Create an empty stack called reverse_stack.
While the original stack is not empty, do the
following:
Pop an element from the original stack and
push it to the reverse_stack.
While the reverse_stack is not empty, do the
following:
Pop an element from the reverse_stack and
print it.
ANSWER-
def print_reverse(stack):
reverse_stack = []
while not len(stack) == 0:
reverse_stack.append(stack.pop())
while not len(reverse_stack) == 0:
print(reverse_stack.pop())
stack = [1, 2, 3, 4, 5]
print("The original stack is:")
print(stack)
print("The reversed stack is:")
print_reverse(stack)
OUTPUT
THANKYOU

You might also like