Computer Science (2024-25)
CLASS XII Code No. 083
Python Programming
Suggested Practical List:
1. Read a text file line by line and display each word separated by a #.
File content:
I love programming
Python is amazing
Coding:
def display_words_with_hash():
try:
# Open the file in read mode
with open('input.txt', 'r') as file:
# Read the file line by line
for line in file:
# Split the line into words
words = line.split()
# Join the words with a '#' separator
output = '#'.join(words)
# Print the formatted output
print(output)
except FileNotFoundError:
print("The file 'input.txt' was not found.")
Output:
I#love#programming
Python#is#amazing
2. Read a text file and display the number of vowels/consonants/uppercase/lowercase characters in the file.
File content:
Hello World!
Coding:
def count_characters():
try:
# Open the file in read mode
with open('input.txt', 'r') as file:
# Initialize counters
vowels = 0
consonants = 0
uppercase = 0
lowercase = 0
# Read the file character by character
for line in file:
for char in line:
if char.isalpha(): # Check if the character is a letter
if char in 'AEIOUaeiou': # Vowels
vowels += 1
else: # Consonants
consonants += 1
# Check if the character is uppercase or lowercase
if char.isupper():
uppercase += 1
elif char.islower():
lowercase += 1
# Display the results
print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")
print(f"Uppercase characters: {uppercase}")
print(f"Lowercase characters: {lowercase}")
except FileNotFoundError:
print("The file 'input.txt' was not found.")
Output:
Vowels: 3
Consonants: 7
Uppercase characters: 2
Lowercase characters: 8
3. Remove all the lines that contain the character 'a' in a file and write it to another file.
input.txt content:
Apple
Banana
Cherry
Mango
Pineapple
Grape
Coding:
def remove_lines_with_a():
try:
# Open the input file in read mode and output file in write mode
with open('input.txt', 'r') as infile, open('output.txt', 'w') as outfile:
# Read the file line by line
for line in infile:
# Check if 'a' or 'A' is not present in the line
if 'a' not in line and 'A' not in line:
# Write the line to the output file if it doesn't contain 'a' or 'A'
outfile.write(line)
print("Lines without 'a' have been written to 'output.txt'.")
except FileNotFoundError:
print("The file 'input.txt' was not found.")
Output:
Cherry
Grape
4. 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.
Coding:
import pickle
# Function to create a binary file with names and roll numbers
def create_binary_file():
try:
# Open the binary file in write mode (wb)
with open('students.dat', 'wb') as file:
# Sample data (list of tuples with name and roll number)
students = [
("Alice", 101),
("Bob", 102),
("Charlie", 103),
("David", 104)
]
# Dump the list of students to the binary file
pickle.dump(students, file)
print("Binary file 'students.dat' created successfully.")
except Exception as e:
print(f"Error: {e}")
# Function to search for a student by roll number and display the name
def search_roll_number(roll_number):
try:
# Open the binary file in read mode (rb)
with open('students.dat', 'rb') as file:
# Load the list of students from the binary file
students = pickle.load(file)
# Search for the student by roll number
found = False
for student in students:
if student[1] == roll_number:
print(f"Student found: Name = {student[0]}, Roll Number = {student[1]}")
found = True
break
# If roll number is not found, display appropriate message
if not found:
print(f"Roll number {roll_number} not found.")
except FileNotFoundError:
print("The binary file 'students.dat' was not found.")
except Exception as e:
print(f"Error: {e}")
# Create the binary file
create_binary_file()
# Search for a student by roll number
roll_number_to_search = int(input("Enter the roll number to search: "))
search_roll_number(roll_number_to_search)
Input:
Enter the roll number to search: 103
Output:
Binary file 'students.dat' created successfully.
Student found: Name = Charlie, Roll Number = 103
Input:
Enter the roll number to search: 105
Output2: If the roll number entered is not in the file, the output will be:
Roll number 105 not found.
5. Create a binary file with roll number, name and marks. Input a roll number and update the marks.
Coding:
import pickle
# Function to create a binary file with roll number, name, and marks
def create_binary_file():
try:
# Open the binary file in write mode (wb)
with open('students.dat', 'wb') as file:
# Sample data: List of tuples with (roll number, name, marks)
students = [
(101, "Alice", 85),
(102, "Bob", 78),
(103, "Charlie", 92),
(104, "David", 88)
]
# Dump the list of students to the binary file
pickle.dump(students, file)
print("Binary file 'students.dat' created successfully.")
except Exception as e:
print(f"Error: {e}")
# Function to update marks of a student by roll number
def update_marks(roll_number, new_marks):
try:
# Open the binary file in read mode first to load the data
with open('students.dat', 'rb') as file:
# Load the list of students from the binary file
students = pickle.load(file)
# Flag to check if roll number was found
found = False
# Update the marks if the roll number is found
for i in range(len(students)):
if students[i][0] == roll_number:
students[i] = (students[i][0], students[i][1], new_marks) # Update the tuple with new marks
found = True
break
if found:
# If the roll number is found and updated, write the updated list back to the file
with open('students.dat', 'wb') as file:
pickle.dump(students, file)
print(f"Marks updated for Roll Number {roll_number}.")
else:
print(f"Roll number {roll_number} not found.")
except FileNotFoundError:
print("The binary file 'students.dat' was not found.")
except Exception as e:
print(f"Error: {e}")
# Create the binary file with initial data
create_binary_file()
# Input roll number and new marks from the user
roll_number_to_update = int(input("Enter the roll number to update marks: "))
new_marks = int(input(f"Enter the new marks for Roll Number {roll_number_to_update}: "))
# Call the function to update marks
update_marks(roll_number_to_update, new_marks)
Input:
Enter the roll number to update marks: 103
Enter the new marks for Roll Number 103: 95
Output:
Binary file 'students.dat' created successfully.
Marks updated for Roll Number 103.
Input:
Enter the roll number to search: 105
Output2: If the roll number entered is not in the file, the output will be:
Roll number 105 not found.
6. Write a random number generator that generates random numbers between 1 and 6 (simulates a dice).
Coding:
import random
def roll_dice():
# Generate a random number between 1 and 6
return random.randint(1, 6)
# Simulate a dice roll
result = roll_dice()
print(f"Dice rolled: {result}")
Output:
Dice rolled: 4
7. Write a Python program to implement a stack using list.
Coding:
class Stack:
def __init__(self):
# Initialize an empty list to store stack elements
self.stack = []
# Push element onto the stack
def push(self, element):
self.stack.append(element)
print(f"{element} pushed to stack")
# Pop element from the stack
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
return "Stack is empty"
# Peek at the top element of the stack
def peek(self):
if not self.is_empty():
return self.stack[-1]
else:
return "Stack is empty"
# Check if the stack is empty
def is_empty(self):
return len(self.stack) == 0
# Display the stack
def display(self):
if not self.is_empty():
print("Stack elements are:", self.stack)
else:
print("Stack is empty")
# Create a stack object
stack = Stack()
# Perform operations on the stack
stack.push(10)
stack.push(20)
stack.push(30)
stack.display()
print(f"Top element is {stack.peek()}")
print(f"Popped element is {stack.pop()}")
stack.display()
Output:
10 pushed to stack
20 pushed to stack
30 pushed to stack
Stack elements are: [10, 20, 30]
Top element is 30
Popped element is 30
Stack elements are: [10, 20]
8. Create a CSV file by entering user-id and password, read and search the password for given userid.
CSV File Format (users.csv):
UserID,Password
john123,password1
alice456,secret123
Coding:
import csv
# Function to create a CSV file with user-id and password
def create_csv_file():
with open('users.csv', mode='w', newline='') as file:
writer = csv.writer(file)
# Writing header row
writer.writerow(["UserID", "Password"])
# Adding user IDs and passwords
while True:
user_id = input("Enter User ID (or 'stop' to finish): ")
if user_id.lower() == 'stop':
break
password = input("Enter Password: ")
writer.writerow([user_id, password])
print("CSV file 'users.csv' created successfully.")
# Function to search for a password by user-id
def search_password(user_id_to_search):
try:
with open('users.csv', mode='r') as file:
reader = csv.reader(file)
# Skip the header row
next(reader)
# Search for the user ID and print the corresponding password
for row in reader:
if row[0] == user_id_to_search:
print(f"Password for User ID {user_id_to_search} is: {row[1]}")
return
print(f"User ID {user_id_to_search} not found.")
except FileNotFoundError:
print("The file 'users.csv' was not found.")
# Create the CSV file with user IDs and passwords
create_csv_file()
# Input user ID to search for
user_id_to_search = input("Enter the User ID to search for: ")
search_password(user_id_to_search)
Input/Output:
Creating the CSV file:
Enter User ID (or 'stop' to finish): john123
Enter Password: password1
Enter User ID (or 'stop' to finish): alice456
Enter Password: secret123
Enter User ID (or 'stop' to finish): stop
CSV file 'users.csv' created successfully.
Searching for a password:
Enter the User ID to search for: john123
Password for User ID john123 is: password1
If the user ID is not found, it will output:
User ID unknown_user not found.
9. Database Management
Create a student table and insert data. Implement the following SQL commands on the student table:
o ALTER table to add new attributes / modify data type / drop attribute
o UPDATE table to modify data o ORDER By to display data in ascending / descending order o DELETE to
remove tuple(s)
o GROUP BY and find the min, max, sum, count and average
● Similar exercise may be framed for other cases.
● Integrate SQL with Python by importing suitable module.
Python Script:
import sqlite3
# Connect to SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('school.db')
# Create a cursor object to execute SQL commands
cur = conn.cursor()
# 1. Create the student table
cur.execute('''
CREATE TABLE IF NOT EXISTS student (
roll_no INTEGER PRIMARY KEY,
name TEXT,
age INTEGER,
marks INTEGER
)
''')
print("Student table created successfully.")
# 2. Insert some initial data into the student table
students = [
(101, 'Alice', 18, 85),
(102, 'Bob', 19, 90),
(103, 'Charlie', 18, 78),
(104, 'David', 20, 92),
(105, 'Eva', 19, 88)
]
cur.executemany('INSERT OR IGNORE INTO student VALUES (?, ?, ?, ?)', students)
print("Initial data inserted into the student table.")
# 3. ALTER TABLE: Add a new column for 'gender'
cur.execute('ALTER TABLE student ADD COLUMN gender TEXT')
print("Column 'gender' added to the student table.")
# 4. UPDATE the table to modify data (e.g., add gender values)
cur.execute("UPDATE student SET gender = 'F' WHERE name = 'Alice'")
cur.execute("UPDATE student SET gender = 'M' WHERE name = 'Bob'")
cur.execute("UPDATE student SET gender = 'M' WHERE name = 'Charlie'")
cur.execute("UPDATE student SET gender = 'M' WHERE name = 'David'")
cur.execute("UPDATE student SET gender = 'F' WHERE name = 'Eva'")
print("Updated gender data in the student table.")
# 5. ORDER BY: Display data in ascending/descending order based on marks
print("Students ordered by marks in ascending order:")
cur.execute("SELECT * FROM student ORDER BY marks ASC")
for row in cur.fetchall():
print(row)
print("\nStudents ordered by marks in descending order:")
cur.execute("SELECT * FROM student ORDER BY marks DESC")
for row in cur.fetchall():
print(row)
# 6. DELETE: Remove a student (e.g., student with roll_no = 103)
cur.execute("DELETE FROM student WHERE roll_no = 103")
print("Deleted student with roll number 103.")
# 7. GROUP BY gender and calculate min, max, sum, count, and average marks
print("\nGROUP BY gender - calculating min, max, sum, count, and average marks:")
cur.execute('''
SELECT gender, MIN(marks), MAX(marks), SUM(marks), COUNT(*), AVG(marks)
FROM student
GROUP BY gender
''')
for row in cur.fetchall():
print(f"Gender: {row[0]}, Min: {row[1]}, Max: {row[2]}, Sum: {row[3]}, Count: {row[4]}, Avg: {row[5]}")
# Commit the transaction
conn.commit()
# Close the connection
conn.close()
Output:
Student table created successfully.
Initial data inserted into the student table.
Column 'gender' added to the student table.
Updated gender data in the student table.
Students ordered by marks in ascending order:
(103, 'Charlie', 18, 78, 'M')
(101, 'Alice', 18, 85, 'F')
(105, 'Eva', 19, 88, 'F')
(102, 'Bob', 19, 90, 'M')
(104, 'David', 20, 92, 'M')
Students ordered by marks in descending order:
(104, 'David', 20, 92, 'M')
(102, 'Bob', 19, 90, 'M')
(105, 'Eva', 19, 88, 'F')
(101, 'Alice', 18, 85, 'F')
(103, 'Charlie', 18, 78, 'M')
Deleted student with roll number 103.
GROUP BY gender - calculating min, max, sum, count, and average marks:
Gender: F, Min: 85, Max: 88, Sum: 173, Count: 2, Avg: 86.5
Gender: M, Min: 90, Max: 92, Sum: 182, Count: 2, Avg: 91.0
---- End -----