Name :
Krishna goel
Class :
12 b (non – medical)
Project :
Computer science
practical file
School :
Virendra public school
PRACTICAL – 01
1) Write a program to enter the string and to check if it’s
palindrome or not using loop.
# Source code :-
# Function to check if a string is palindrome
def is_palindrome(s):
# Convert the string to lowercase to make the check
case-insensitive
s = s.lower()
# Initialize start and end pointers
start = 0
end = len(s) - 1
# Loop to compare characters from start and end
while start < end:
# Skip non-alphanumeric characters
if not s[start].isalnum():
start += 1
continue
if not s[end].isalnum():
end -= 1
continue
# Compare characters
if s[start] != s[end]:
return False
# Move pointers closer to the center
start += 1
end -= 1
return True
# Input string from the user
user_input = input("Enter a string: ")
# Check if the input string is a palindrome
if is_palindrome(user_input):
print("The string is a palindrome!")
else:
print("The string is not a palindrome.")
OUTPUT
PRACTICAL – 02
2) Read a text file line by line and display each word
separated by #.
def display_words_with_hash(filename):
try:
with open(filename, 'r') as file:
for line in file:
words = line.split()
result = '#'.join(words)
print(result)
except FileNotFoundError:
print(f"File '{filename}' not found.")
filename = input("Enter the name of the text file (with extension):
")
display_words_with_hash(filename)
Practical – 03
3)Read a text file and displace the number of vowels/
consonants/ uppercase/lowercase in that file.
def count characters(filename):
vowels = "aeiouAEIOU"
num_vowels = 0
num_consonants = 0
num_uppercase = 0
num_lowercase = 0
try:
with open(filename, 'r') as file:
content = file.read()
for char in content:
if char.isalpha():
if char in vowels:
num_vowels += 1
else:
num_consonants += 1
if char.isupper():
num_uppercase += 1
elif char.islower():
num_lowercase += 1
print(f"Number of vowels: {num_vowels}")
print(f"Number of consonants: {num_consonants}")
print(f"Number of uppercase letters: {num_uppercase}")
print(f"Number of lowercase letters: {num_lowercase}")
except FileNotFoundError:
print(f"File '{filename}' not found.")
filename = input("Enter the name of the text file (with extension):
")
count_characters(filename)
Practical – 04
4)Write a random number generator that generates random numbers
between 1 and 6 (simulates a dice).
import random
# Function to simulate a dice roll
def roll_dice():
return random.randint(1, 6)
# Rolling the dice
dice_result = roll_dice()
# Display the result
print(f"The dice rolled: {dice_result}")
Practical – 05
5)Write a recursive code to find the sum of all elements of a list.
def recursive_sum(lst):
if not lst:
return 0
return lst[0] + recursive_sum(lst[1:])
numbers = [1, 2, 3, 4, 5]
print("Sum of all elements:", recursive_sum(numbers))
Practical – 06
6) write a python function sin(x,n) to calculate the value of sin(x) using its
Taylor series expansion upto n terms. Compare the values of sin(x) for
different values of n with the correct value.
import math
def sin(x, n):
"""Calculate sin(x) using Taylor series expansion up to n terms."""
sin_x = 0
for i in range(n):
term = ((-1) ** i) * (x ** (2 * i + 1)) / math.factorial(2 * i + 1)
sin_x += term
return sin_x
x = math.pi / 3
n_values = [1, 2, 5, 10, 20]
print(f"True value of sin({x}): {math.sin(x)}")
for n in n_values:
calculated_sin = sin(x, n)
print(f"sin({x}) with {n} terms: {calculated_sin}")
Practical – 07
7)Program to write roll no , name and marks of a student
in a data file Marks.dat.
def write_student_data(filename, roll_no, name, marks):
"""Writes student data to a file."""
with open(filename, 'a') as file:
file.write(f"Roll No: {roll_no}\n")
file.write(f"Name: {name}\n")
file.write(f"Marks: {marks}\n")
file.write("-" * 30 + "\n")
filename = 'Marks.dat'
roll_no = input("Enter Roll Number: ")
name = input("Enter Student Name: ")
marks = input("Enter Marks: ")
write_student_data(filename, roll_no, name, marks)
print(f"Data for roll number {roll_no} has been written to {filename}.")
Practical – 08
8) write a program to read data from data file in read
mode and count the particular word occurrences in given
string.
def count_word_occurrences(filename, word_to_count):
"""Reads a file and counts the occurrences of a specified word."""
try:
with open(filename, 'r') as file:
content = file.read()
words = content.lower().split()
word_count = words.count(word_to_count.lower())
return word_count
except FileNotFoundError:
print(f"Error: The file {filename} does not exist.")
return 0
filename = 'C:/Users/nar/testingfile.txt'
word_to_count = input("Enter the word to count: ")
occurrences = count_word_occurrences(filename, word_to_count)
print(f"The word '{word_to_count}' occurs {occurrences} times in the file {filename}.")
Practical – 09
9) Remove all the lines that contain the character ‘a’ in a file .
def remove_lines_containing_char(filename, char_to_remove):
try:
with open(filename, 'r') as file:
lines = file.readlines()
filtered_lines = [line for line in lines if char_to_remove not in line]
with open(filename, 'w') as file:
file.writelines(filtered_lines) the file
print(f"Lines containing '{char_to_remove}' have been removed from
{filename}.")
except FileNotFoundError:
print(f"Error: The file {filename} does not exist.")
except IOError as e:
print(f"Error: {e}")
filename = 'makrs.dat'
char_to_remove = 'a'
remove_lines_containing_char(filename, char_to_remove)
Practical – 10
10) 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.
import pickle
# Function to add data to the binary file
def add_students(filename, students):
with open(filename, 'wb') as file:
pickle.dump(students, file)
# Function to search for a roll number and display the corresponding name
def search_student(filename, roll_number):
try:
with open(filename, 'rb') as file:
students = pickle.load(file)
for student in students:
if student['roll'] == roll_number:
return f"Name: {student['name']}, Roll No: {student['roll']}"
return "Roll number not found."
except FileNotFoundError:
return "File not found."
#Example usage
filename = 'students1.dat'
# Create a list of students
students_list = [
{'name': 'John Doe', 'roll': 101},
{'name': 'Jane Smith', 'roll': 102},
{'name': 'Alice Johnson', 'roll': 103}
# Add students to the file
add_students(filename, students_list)
# Search for a student by roll number
roll_number = int(input("Enter the roll number to search: "))
result = search_student(filename, roll_number)
print(result)
Practical – 11
11)Create a binary file with roll number , name and marks. Input a roll
no and update the marks.
import pickle
# Function to add data to the binary file
def add_students(filename, students):
with open(filename, 'wb') as file:
pickle.dump(students, file)
# Function to search for a student by roll number and update marks
def update_marks(filename, roll_number, new_marks):
try:
with open(filename, 'rb') as file:
students = pickle.load(file)
# Flag to check if the student is found
student_found = False
# Update marks if roll number is found
for student in students:
if student['roll'] == roll_number:
student['marks'] = new_marks
student_found = True
break
if student_found:
with open(filename, 'wb') as file:
pickle.dump(students, file)
return f"Marks updated for Roll No: {roll_number}."
else:
return "Roll number not found."
except FileNotFoundError:
return "File not found."
# Example usage
filename = 'students.dat'
# Create a list of students
students_list = [
{'name': 'John Doe', 'roll': 101, 'marks': 85},
{'name': 'Jane Smith', 'roll': 102, 'marks': 90},
{'name': 'Alice Johnson', 'roll': 103, 'marks': 88}
# Add students to the file initially
add_students(filename, students_list)
# Input roll number and new marks to update
roll_number = int(input("Enter the roll number to update marks: "))
new_marks = int(input("Enter the new marks: "))
result = update_marks(filename, roll_number, new_marks)
print(result)
Practical – 12
12) Create a CSV file by entering user – id and password, read and search the
password for a given user – id.
import csv
# Function to add users to the CSV file
def add_user(filename, user_id, password):
with open(filename, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([user_id, password])
print(f"User {user_id} added.")
# Function to search for a password by user ID
def search_password(filename, user_id):
try:
with open(filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
if row[0] == user_id:
return f"Password for user {user_id}: {row[1]}"
return "User ID not found."
except FileNotFoundError:
return "File not found."
# Example usage
filename = 'users.csv'
# Input new users
user_id = input("Enter User ID: ")
password = input("Enter Password: ")
add_user(filename, user_id, password)
# Search for a user by user ID
search_user_id = input("Enter the User ID to search for the password: ")
result = search_password(filename, search_user_id)
print(result)
Practical – 13
13) Count the number of records and column names present in CSV file.
import csv
# Function to count the number of records and display column names
def count_records_and_columns(filename):
try:
with open(filename, 'r') as file:
reader = csv.reader(file)
# Extract the header (column names)
columns = next(reader)
num_columns = len(columns)
# Count the number of records (rows)
num_records = sum(1 for row in reader)
print(f"Column names: {columns}")
print(f"Number of columns: {num_columns}")
print(f"Number of records: {num_records}")
except FileNotFoundError:
print("File not found.")
# Example usage
filename = 'users.csv'
count_records_and_columns(filename)
Practical – 14
14) Write a program to implement a stack for the
employee details( empno,name)
class EmployeeStack:
def __init__(self):
self.stack = []
# Function to push employee details onto the stack
def push(self, empno, name):
employee = {'empno': empno, 'name': name}
self.stack.append(employee)
print(f"Employee {name} with Employee Number {empno} added
to the stack.")
# Function to pop employee details from the stack
def pop(self):
if not self.is_empty():
employee = self.stack.pop()
print(f"Employee {employee['name']} with Employee Number
{employee['empno']} removed from the stack.")
return employee
else:
print("Stack is empty, no employee to pop.")
return None
# Function to view the top employee in the stack
def peek(self):
if not self.is_empty():
employee = self.stack[-1]
print(f"Top Employee: {employee['name']} with Employee
Number {employee['empno']}")
return employee
else:
print("Stack is empty.")
return None
# Function to check if the stack is empty
def is_empty(self):
return len(self.stack) == 0
# Function to display all employees in the stack
def display(self):
if self.is_empty():
print("Stack is empty.")
else:
print("Employees in Stack (from top to bottom):")
for employee in reversed(self.stack):
print(f"Employee Number: {employee['empno']}, Name:
{employee['name']}")
# Example usage
stack = EmployeeStack()
# Push employees onto the stack
stack.push(101, "John Doe")
stack.push(102, "Jane Smith")
stack.push(103, "Alice Johnson")
# Display the stack
stack.display()
# Peek the top employee
stack.peek()
# Pop an employee from the stack
stack.pop()
Practical – 15
15)Integrate MySQL with python by importing the MySQL module and
add records of student and display all the record.
import mysql.connector
# Function to connect to MySQL database
def connect_to_db():
try:
connection = mysql.connector.connect(
host='localhost',
user='root',
password='brohaving',
database='student_db'
if connection.is_connected():
print("Successfully connected to the database.")
return connection
except mysql.connector.Error as e:
print(f"Error connecting to MySQL: {e}")
return None
# Function to create a table if it doesn't already exist
def create_student_table(connection):
cursor = connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
roll_no INT
)
""")
connection.commit()
print("Table 'students' ensured.")
# Function to add a student record to the table
def add_student(connection, name, roll_no):
cursor = connection.cursor()
sql = "INSERT INTO students (name, roll_no) VALUES (%s, %s)"
val = (name, roll_no)
cursor.execute(sql, val)
connection.commit()
print(f"Student {name} with Roll No {roll_no} added.")
# Function to display all student records
def display_students(connection):
cursor = connection.cursor()
cursor.execute("SELECT * FROM students")
records = cursor.fetchall()
if len(records) > 0:
print("Student Records:")
for record in records:
print(f"ID: {record[0]}, Name: {record[1]}, Roll No: {record[2]}")
else:
print("No records found.")
# Example usage
connection = connect_to_db()
if connection:
# Ensure the table is created
create_student_table(connection)
# Add student records
add_student(connection, 'Sparsh', 101)
add_student(connection, 'Sonu', 102)
add_student(connection, 'Vikas', 104)
# Display all records
display_students(connection)
# Close the connection
connection.close()