D XII CS Practical List 2024-25
D XII CS Practical List 2024-25
Marks
S No Unit Name (Total=30)
Lab Test:
8
1. Python program (60% logic + 20% documentation + 20% code quality)
1
2. SQL queries (4 queries based on one or two tables) 4
2 Report file: 7
● Minimum 15 Python programs.
● SQL Queries – Minimum 5 sets using one table / two tables.
● Minimum 4 programs based on Python - SQL connectivity
3 Project (using concepts learnt in Classes 11 and 12) 8
4 Viva voce 3
TOTAL 30 Marks
Suggestive answer:
# Open the file in read mode
with open("myfile.txt", "r") as file:
# Read each line from the file
for line in file:
# Split the line into words
words = line.split()
# Join the words with '#' and print them
print("#".join(words))
Explanation:
# Example usage
count_characters('myfile.txt')
Explanation:
Make sure that the file myfile.txt is in the same directory as the Python script or provide the correct path.
4. Remove all the lines that contain the character `a' in a file and write it to another file.
Suggestive answer:
def remove_lines_with_a(input_file, output_file):
with open(input_file, 'r') as infile:
lines = infile.readlines()
with open(output_file, 'w') as outfile:
for line in lines:
if 'a' not in line:
outfile.write(line)
# Example usage:
input_file = 'input.txt' # Replace with your input file name
output_file = 'output.txt' # Replace with your desired output file name
remove_lines_with_a(input_file, output_file)
How it works:
1. The program opens the input file and reads all lines.
2. It then opens the output file for writing.
3. For each line in the input file, it checks if the character 'a' is not present.
4. If 'a' is not in the line, it writes that line to the output file.
Usage:
Make sure to replace input.txt and output.txt with your actual file names. You can run this script in a
Python environment where you have access to the specified files.
5. Write a program to create a text file and print the lines starting with ‘T’ or ‘P’. (Both
uppercase and lowercase).
Suggestive answer:
# Create and write to a text file
file_name = 'sample.txt'
with open(file_name, 'w') as file:
file.write("This is the first line.\n")
file.write("Another line starts with A.\n")
file.write("Perfectly positioned line.\n")
file.write("Just another line.\n")
file.write("To test the output.\n")
file.write("Possible line here.\n")
file.write("Yet another line.\n")
# Read the file and print lines that start with 'T' or 'P'
with open(file_name, 'r') as file:
for line in file:
if line.startswith(('T', 't', 'P', 'p')):
print(line.strip())
Explanation:
1. Creating the File: The program first opens a file named sample.txt in write mode and writes several
lines to it.
2. Reading the File: It then opens the same file in read mode and iterates through each line.
3. Filtering Lines: The startswith method is used to check if the line starts with 'T', 't', 'P', or 'p'.
4. Printing: If the condition is met, it prints the line without leading or trailing whitespace.
6. Read a text file to print the frequency of the word ‘He’ and ‘She’ found in the file.
Suggestive answer:
# Open the file (example.txt)
file = open('example.txt', 'r') # 'r' mode is for reading
Explanation:
1. Opening the file: We use open() to open the file in read mode ('r').
2. Reading the file content: The .read() method reads the entire content of the file into a single string.
3. Closing the file: It's important to close the file after reading to free system resources.
4. Splitting the content: The split() method splits the content by whitespace, returning a list of words.
5. Counting occurrences: We loop through the list of words, and for each word, we check if it is "He" or
"She". We increment the respective counters.
6. Displaying results: The print() function is used to display the counts of "He" and "She".
7. Create a binary file with name and roll number. Search for a given roll number and
display the name, if not found display appropriate message.
Suggestive answer:
import pickle
# Function to create a binary file with student records (name and roll number)
def create_file(file_name):
# Open the binary file in write mode
file = open(file_name, "wb")
# Function to search for a roll number in the binary file and display the name
def search_roll(file_name, roll_no):
# Open the binary file in read mode
file = open(file_name, "rb")
Explanation:
# Load all the records into a list and check for the roll number
try:
while True:
record = pickle.load(file)
if record['roll_no'] == roll_no:
record['marks'] = new_marks # Update marks if roll number matches
temp_records.append(record)
except EOFError:
pass # End of file reached
Explanation:
def read_csv_file(file_path):
file = open(file_path, mode='r') # Open the file without 'with open()'
reader = csv.reader(file) # Read the file using csv.reader
details = []
for row in reader:
details.append(row) # Store rows in a list instead of printing
Explanation:
1. Opening the file: The open() function is used without with, which means we have to manually close
the file after reading it.
2. Reading the CSV: The csv.reader() function takes the file object and reads it row by row, converting
each row into a list of values.
3. Storing the rows: Each row is appended to the details list.
4. Returning the data: After reading all rows, the function returns the details list, which can be used
later to display or process the CSV data.
10. Read a CSV file (containing item no, name, rate, QOH) from hard disc and print all the
items whose rate is between Rs 500 and Rs 1000.
Suggestive answer:
import csv
# Open the CSV file (without using 'with open()')
file = open('items.csv', 'r')
# Initialize the CSV reader
reader = csv.reader(file)
# Skip the header (assuming the file has headers)
next(reader)
# Loop through the rows and print items with rate between 500 and 1000
for row in reader:
item_no, name, rate, QOH = row
rate = float(rate) # Convert rate from string to float
if 500 <= rate <= 1000:
print("Item No:", item_no, "Name:", name, "Rate:", rate, "QOH:", QOH)
# Close the file
file.close()
Explanation:
1. CSV Reader: Python’s built-in csv module is used to handle the reading of CSV files.
2. Opening the file:
o Instead of using with open(), we explicitly open the file using open(). This allows us to
manually manage the file closing.
o open('items.csv', 'r'): This opens the file in read mode ('r').
3. Skipping the header:
o Assuming the file has headers (like "item no, name, rate, QOH"), the next(reader) function
skips the first row (header).
4. Iterating through rows:
o We loop through the rows in the CSV file, and each row is a list of strings. We unpack this list
into individual variables: item_no, name, rate, and QOH.
o Since rate is read as a string, we convert it to a float before comparison (rate =
float(rate)).
5. Filtering by rate:
o We check if the rate is between 500 and 1000 using the condition 500 <= rate <= 1000. If
true, the details of the item are printed.
6. Closing the file:
o After reading the file, we close it using file.close() to free up resources.
Expected Output:
Item No: 101 Name: Pen Rate: 750.0 QOH: 50
Item No: 103 Name: Stapler Rate: 900.0 QOH: 10
11. Create a CSV file by entering user-id and password, read and search the password for
given userid.
Suggestive answer:
import csv
# Function to read the CSV file and search for the password using user ID
def search_password(user_id):
filename = 'users.csv'
# Main program
create_user_csv() # Create a new user entry
user_id_to_search = input("Enter User ID to search for the password: ")
search_password(user_id_to_search) # Search for the password
Explanation:
1. Import CSV Module: We import the csv module to handle CSV file operations.
2. Function to Create CSV File (create_user_csv):
o We open a file named users.csv in write mode ('w').
o We create a CSV writer object to write data into the file.
o We prompt the user to enter a user ID and a password.
o We use writer.writerow() to write the user ID and password as a row in the CSV file.
o Finally, we close the file to save the changes.
3. Function to Search Password (search_password):
o We open the same file in read mode ('r').
o We create a CSV reader object to read the contents of the file.
o We iterate over each row of the CSV file to check if the first element (user ID) matches the
provided user ID.
o If a match is found, we print the corresponding password. If no match is found after checking all
rows, we notify the user that the user ID was not found.
o Finally, we close the file.
4. Main Program:
o We call create_user_csv() to allow the user to enter their credentials.
o We prompt the user to enter a user ID to search for the corresponding password, calling
search_password() to perform the search.
12. Write a random number generator that generates random numbers between 1 and 6
(simulates a dice). Throw the two dices for 10 times and print their total.
Suggestive answer:
import random
# Function to simulate rolling two dice
def roll_dice():
# Generate a random number between 1 and 6 for each die
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
# Calculate the total of both dice
total = die1 + die2
return total
# Main program to roll the dice 10 times
for i in range(10):
total = roll_dice() # Call the function to roll the dice
print("Roll", i + 1, "total:", total) # Print the total for this roll
Explanation
Output
When you run this program, it will output something like this:
Roll 1 total: 7
Roll 2 total: 3
Roll 3 total: 8
Roll 4 total: 5
Roll 5 total: 10
Roll 6 total: 4
Roll 7 total: 6
Roll 8 total: 11
Roll 9 total: 9
Roll 10 total: 2
Each line shows the total of the two dice for each roll, which will vary each time you run the
program due to the randomness.
13. Write a Python program to implement a stack using a list data-structure.
Suggestive answer: #menu driven function program of stack using list
def isEmpty(stk):
if len(stk)==0:
return True
else:
return False
def Push(stk,ele):
stk.append(ele)
print("Item Pushed...")
def Pop(stk):
if isEmpty(stk):
print("Stack is empty..Underflow condition..")
else:
print("Poped item is:",stk.pop())
def Peek(stk):
if isEmpty(stk):
print("Stack is empty..Underflow condition..")
else:
print("Stack Top item is:",stk[-1])
def Display(stk):
if isEmpty(stk):
print("Stack is empty....")
else:
for i in range(len(stk)-1,-1,-1):
print(stk[i])
stack=[]
while True:
print("***Stack Operations***")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
ch=int(input("Enter your choice:"))
if ch==1:
item=int(input("Enter the item to be pushed:"))
Push(stack,item)
if ch==2:
Pop(stack)
if ch==3:
Peek(stack)
if ch==4:
Display(stack)
if ch==5:
break
14. WAP to pass an integer list as stack to a function and push only those elements in the stack
which are divisible by 7.
Suggestive answer:
def push_divisible_by_seven(input_list):
stack = [ ]
if num % 7 == 0:
stack.append(num)
return stack
# Example usage
result_stack = push_divisible_by_seven(integer_list)
Explanation
1. Function Definition:
o We define a function named push_divisible_by_seven that takes an input_list as an
argument.
2. Initialize Stack:
o We initialize an empty list called stack, which will be used to store elements that are divisible
by 7.
3. Loop Through Input List:
o We use a for loop to iterate through each element in the input_list.
4. Check for Divisibility:
o Inside the loop, we check if the current number (num) is divisible by 7 using the modulo
operator (%). If num % 7 == 0, it means num is divisible by 7.
5. Push to Stack:
o If the condition is met, we use the append() method to add the number to the stack.
6. Return Stack:
o After the loop finishes, we return the stack containing all the numbers from the input list that
are divisible by 7.
7. Example Usage:
o We create an example list of integers and call the function with this list. Finally, we print the
elements of the stack that are divisible by 7.
Output
When the above program is run with the provided example list, it will display:
This output shows the elements that were pushed onto the stack, all of which are divisible by 7.
15. Write the definition of a user-defined function `push_even(N)` which accepts a list of integers in a
parameter `N` and pushes all those integers which are even from the list `N` into a Stack named
`EvenNumbers`.
Write function pop_even() to pop the topmost number from the stack and returns it. If the stack is
already empty, the function should display "Empty".
Write function Disp_even() to display all element of the stack without deleting them. If the stack is
empty, the function should display 'None'.
For example: If the integers input into the list `VALUES` are: [10, 5, 8, 3, 12]
Then the stack `EvenNumbers` should store: [10, 8, 12]
Suggestive answer:
# Initialize an empty list to act as a stack
EvenNumbers = [ ]
# Function to push all even numbers from a list into the EvenNumbers stack
def push_even(N):
global EvenNumbers # Using global variable for the stack
for num in N:
if num % 2 == 0: # Check if the number is even
EvenNumbers.append(num) # Push even numbers onto the stack
# Example usage:
VALUES = [ ]
for i in range(5):
VALUES.append(int(input("Enter an integer: "))) # Input list of integers
Explanation:
1. Stack Initialization:
o We use a global list named EvenNumbers to simulate the stack where the even integers are
stored.
2. Function push_even(N):
o The function push_even(N) accepts a list N of integers.
o It checks each number in N using num % 2 == 0 to determine if it is even. If it is, the number is
appended to the EvenNumbers list, which acts as the stack.
3. Function pop_even():
o The pop_even() function removes and returns the topmost element from the stack using the
pop() method.
o If the stack is empty (i.e., the length of the list is zero), it prints "Empty" and returns None.
4. Function Disp_even():
o The Disp_even() function prints the contents of the EvenNumbers stack without modifying it.
o If the stack is empty, it prints "None".
Example Walkthrough:
16. Queries using Create database, Show databases, Use, Create table, Show Tables, Describe,
Rename, Alter, Select, From, Where, Insert, Update commands.
Suggestive answer:
Create a Database:
CREATE DATABASE kviit ;
Rename a Table:
RENAME TABLE students TO school_students ;
3. Query using IN
To find employees working in specific departments: