Cs Practical Files
Cs Practical Files
Cs Practical Files
Write a Program to enter the string and to check if it's palindrome or not
using loop.
def is_palindrome():
rev_s = s[::-1]
if s == rev_s:
print(f"'{s}' is a palindrome.")
else:
is_palindrome()
2. Write a Program to search an element using BINARY search.
def binary_search(arr, x):
l, r = 0, len(arr) - 1
while l <= r:
mid = (l + r) // 2
if arr[mid] == x:
return mid
l = mid + 1
else:
r = mid - 1
return -1
result = binary_search(arr, x)
if result != -1:
else:
def write_data():
pickle.dump(student, f)
write_data()
4. Read a text file line by line and display each word separated by #.
def display_words():
file.write(text)
words = line.split()
print('#'.join(words))
display_words()
5. Read a text file and display the number of vowels / consonants / uppercase /
lowercase characters in the file.
def count_characters():
vowels = "aeiouAEIOU"
consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
file.write(text)
if char.isupper():
upper += 1
if char.islower():
lower += 1
if char in vowels:
vowel_count += 1
if char in consonants:
consonant_count += 1
count_characters()
6. Remove all the lines that contain the character a' in a file and write it to another file.
import os
def remove_lines_with_a():
input_file_name = input("Enter the input file name (with .txt extension): ")
output_file_name = input("Enter the output file name (with .txt extension): ")
print("Enter the text for the input file (type 'E' on a new line to finish):")
while True:
line = input()
if line == 'E':
break
input_file.write(line + '\n')
output_file.write(line)
os.startfile(output_file_name)
remove_lines_with_a()
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.
import pickle
def search_roll():
while True:
if roll_no == 'END':
break
pickle.dump(student, f)
found = False
while True:
try:
student = pickle.load(f)
if student['roll_no'] == roll_no_to_search:
found = True
break
except EOFError:
break
if not found:
search_roll()
8. Create a binary file with roll number, name and marks. Input a roll number
and update the marks.
import pickle
def create_file_with_user_data():
while True:
if roll_no.upper() == 'END':
break
pickle.dump(student, f)
def update_marks():
students = []
while True:
try:
student = pickle.load(f)
if student['roll_no'] == roll_no:
student['marks'] = new_marks
students.append(student)
except EOFError:
break
pickle.dump(student, f)
create_file_with_user_data()
update_marks()
def roll_dice():
roll_dice()
10. Create a CSV file by entering user-id and password, read and search the
password for given user-id.
import csv
def create_csv():
writer = csv.writer(file)
while True:
writer.writerow([user_id, password])
break
def search_password():
reader = csv.reader(file)
found = False
if row[0] == user_id:
print(f"Password: {row[1]}")
found = True
break
if not found:
create_csv()
search_password()
11. Count the number of records and column names present in the CSV file.\
import csv
def count_records_and_columns():
with open(file_name, 'w', newline='') as file: # 'w' mode ensures the file is created fresh every time
writer = csv.writer(file)
while True:
writer.writerow(row)
break
reader = csv.reader(file)
columns = next(reader)
count_records_and_columns()
12. Write a recursive code to find the sum of all elements of a list.
def recursive_sum(lst):
if not lst:
return 0
13. 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
sin_x = 0
for i in range(n):
sign = (-1)**i
return sin_x
And
def __init__(self):
self.stack = []
def is_empty(self):
return len(self.stack) == 0
self.stack.append(item)
print(f"Pushed: {item}")
def pop(self):
if self.is_empty():
print("Stack is empty.")
return None
return self.stack.pop()
def display(self):
if self.is_empty():
print("Stack is empty.")
else:
stack = Stack()
while True:
print("\n1. Push")
print("2. Pop")
print("4. Exit")
choice = input("Choose an option: ")
if choice == '1':
stack.push(item)
popped = stack.pop()
print(f"Popped: {popped}")
stack.display()
print("Exiting program.")
break
else:
stack = []
while True:
print("4. Exit")
if choice == 1:
elif choice == 2:
if not stack:
print("Stack is empty!")
else:
emp = stack.pop()
elif choice == 3:
print("Stack:", stack)
elif choice == 4:
break
else:
print("Invalid choice!")
employee_stack()
17. 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():
count = 0
words = line.split()
count += words.count(word_to_count)
count_word_occurrences()
18. Write a python program using function POP (Arr), where Arr is a stack
implemented by a list of numbers. The function returns the value deleted from
the stack.
def POP(Arr):
if Arr:
return Arr.pop()
else:
19. Write a python program using function PUSH (Arr), where Arr is a list of
numbers. From this list push all numbers divisible by 5 into a stack
implemented by using a list. Display the stack if it has at least one element,
otherwise display appropriate error message.
def PUSH(Arr):
if stack:
print("Stack:", stack)
else:
PUSH(Arr)
20. Integrate MySQL with Python by importing the MySQL module and add records of student and
display all the record.
21. Integrate MySQL with Python by importing the MySQL module to search student using rollno,
name, age, class and if present in table display the record, if not display appropriate method.
22. Integrate SQL with python by importing the MySQL module to search a student using rollno,
delete the record.
23. Integrate SQL with Python by importing the MySQL module to search a student using roll no. ,
update the record.
import pymysql
def create_connection():
connection = pymysql.connect(
host='localhost',
user='root',
password='cherry',
database='studentdatab'
return connection
def create_table(connection):
create_students_table = """
name VARCHAR(100),
age INT,
class VARCHAR(10)
);
"""
cursor = connection.cursor()
cursor.execute(create_students_table)
connection.commit()
def add_student(connection):
query = "INSERT INTO students (roll_no, name, age, class) VALUES (%s, %s, %s, %s)"
cursor = connection.cursor()
connection.commit()
def display_all_students(connection):
cursor = connection.cursor()
rows = cursor.fetchall()
print(row)
def search_student(connection):
cursor = connection.cursor()
cursor.execute(query, (roll_no,))
student = cursor.fetchone()
if student:
else:
cursor = connection.cursor()
cursor.execute(query, (roll_no,))
connection.commit()
if cursor.rowcount > 0:
else:
def update_student(connection):
cursor = connection.cursor()
cursor.execute(query, (roll_no,))
student = cursor.fetchone()
if student:
if name == "":
name = student[1]
if age == "":
age = student[2]
else:
age = int(age)
if class_name == "":
class_name = student[3]
update_query = """
UPDATE students
WHERE roll_no = %s
"""
connection.commit()
else:
def main():
connection = create_connection()
create_table(connection)
while True:
print("\nMenu:")
print("6. Exit")
if choice == '1':
add_student(connection)
search_student(connection)
delete_student(connection)
update_student(connection)
break
else:
connection.close()
if __name__ == "__main__":
main()