Cs Practical Files

Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

1.

Write a Program to enter the string and to check if it's palindrome or not
using loop.
def is_palindrome():

s = input("Enter a string: ")

rev_s = s[::-1]

if s == rev_s:

print(f"'{s}' is a palindrome.")

else:

print(f"'{s}' is not a palindrome.")

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

elif arr[mid] < x:

l = mid + 1

else:

r = mid - 1

return -1

arr = sorted([int(x) for x in input("Enter sorted elements separated by spaces: ").split()])

x = int(input("Enter element to search: "))

result = binary_search(arr, x)

if result != -1:

print(f"Element found at index {result}")

else:

print("Element not found in the array")


3. Program to write roll no. name and marks of a student in a data file
Marks.dat.
import pickle

def write_data():

roll_no = input("Enter roll number: ")

name = input("Enter name: ")

marks = float(input("Enter marks: "))

with open('Markss.dat', 'wb') as f:

student = {'roll_no': roll_no, 'name': name, 'marks': marks}

pickle.dump(student, f)

print("Data written to a new file.")

write_data()
4. Read a text file line by line and display each word separated by #.
def display_words():

file_name = input("Enter file name: ")

with open(file_name, 'w') as file:

text = input("Enter text for the file: ")

file.write(text)

with open(file_name, 'r') as file:

for line in file:

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"

upper, lower, vowel_count, consonant_count = 0, 0, 0, 0

file_name = input("Enter file name: ")

with open(file_name, 'w') as file:

text = input("Enter text for the file: ")

file.write(text)

with open(file_name, 'r') as file:

for line in file:

for char in line:

if char.isupper():

upper += 1

if char.islower():

lower += 1

if char in vowels:

vowel_count += 1

if char in consonants:

consonant_count += 1

print(f"Vowels: {vowel_count}, Consonants: {consonant_count}, Uppercase: {upper}, Lowercase:


{lower}")

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): ")

with open(input_file_name, 'w') as input_file:

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

with open(input_file_name, 'r') as input_file, open(output_file_name, 'w') as output_file:

for line in input_file:

if 'a' not in line and 'A' not in line:

output_file.write(line)

print(f"Lines without 'a' have been written to {output_file_name}.")

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

with open('Markings.dat', 'wb') as f:

while True:

roll_no = input("Enter roll number (or type 'END' to finish): ")

if roll_no == 'END':

break

name = input("Enter name: ")

marks = float(input("Enter marks: "))

student = {'roll_no': roll_no, 'name': name, 'marks': marks}

pickle.dump(student, f)

roll_no_to_search = input("Enter roll number to search: ")

found = False

with open('Markings.dat', 'rb') as f:

while True:

try:

student = pickle.load(f)

if student['roll_no'] == roll_no_to_search:

print(f"Name: {student['name']}, Marks: {student['marks']}")

found = True

break

except EOFError:

break

if not found:

print("Roll number 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():

with open('classMarks.dat', 'wb') as f:

print("Enter student data. Type 'END' for roll number to finish.")

while True:

roll_no = input("Enter roll number: ")

if roll_no.upper() == 'END':

break

name = input("Enter name: ")

marks = float(input("Enter marks: "))

student = {'roll_no': roll_no, 'name': name, 'marks': marks}

pickle.dump(student, f)

print("Student data has been saved to Marks.dat.")

def update_marks():

roll_no = input("Enter roll number to update marks: ")

new_marks = float(input("Enter new marks: "))

students = []

with open('classMarks.dat', 'rb') as f:

while True:

try:

student = pickle.load(f)

if student['roll_no'] == roll_no:

student['marks'] = new_marks

print(f"Updated marks for {student['name']}")

students.append(student)

except EOFError:
break

with open('classMarks.dat', 'wb') as f:

for student in students:

pickle.dump(student, f)

create_file_with_user_data()

update_marks()

9. Write a random number generator that generates random numbers between 1


and 6 (simulates a dice).
import random

def roll_dice():

print(f"Random number (1-6): {random.randint(1, 6)}")

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

with open('users.csv', 'w', newline='') as file:

writer = csv.writer(file)

while True:

user_id = input("Enter user ID: ")

password = input("Enter password: ")

writer.writerow([user_id, password])

if input("Add another user? (y/n): ").lower() != 'y':

break

def search_password():

user_id = input("Enter user ID to search: ")

with open('users.csv', 'r') as file:

reader = csv.reader(file)

found = False

for row in reader:

if row[0] == user_id:

print(f"Password: {row[1]}")

found = True

break

if not found:

print("User ID 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():

file_name = input("Enter CSV file name: ")

with open(file_name, 'w', newline='') as file: # 'w' mode ensures the file is created fresh every time

writer = csv.writer(file)

while True:

row = input("Enter row data (comma-separated): ").split(',')

writer.writerow(row)

if input("Add another row? (y/n): ").lower() != 'y':

break

with open(file_name, 'r') as file:

reader = csv.reader(file)

columns = next(reader)

record_count = sum(1 for row in reader)

print(f"Number of columns: {len(columns)}, Number of records: {record_count}")

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

return lst[0] + recursive_sum(lst[1:])

lst = [int(x) for x in input("Enter list elements separated by spaces: ").split()]

print(f"Sum of elements: {recursive_sum(lst)}")

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

def sin_taylor_series(x, n):

sin_x = 0

for i in range(n):

sign = (-1)**i

sin_x += sign * (x**(2*i + 1)) / math.factorial(2*i + 1)

return sin_x

x = float(input("Enter value for x (in radians): "))

n = int(input("Enter number of terms: "))

print(f"sin({x}) calculated using Taylor series: {sin_taylor_series(x, n)}")

print(f"Actual sin({x}) using math.sin: {math.sin(x)}")


14. Write a Python program to implement a stack using a list data-structure.

And

15. Write a menu-driven python program to implement stack operation.


class Stack:

def __init__(self):

self.stack = []

def is_empty(self):

return len(self.stack) == 0

def push(self, item):

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:

print("Stack elements:", self.stack)

stack = Stack()

while True:

print("\n1. Push")

print("2. Pop")

print("3. Display Stack")

print("4. Exit")
choice = input("Choose an option: ")

if choice == '1':

item = input("Enter item to push: ")

stack.push(item)

elif choice == '2':

popped = stack.pop()

if popped is not None:

print(f"Popped: {popped}")

elif choice == '3':

stack.display()

elif choice == '4':

print("Exiting program.")

break

else:

print("Invalid choice. Please try again.")


16. Write a program to implement a stack for the employee details (empno,
name)
def employee_stack():

stack = []

while True:

print("\n1. Push Employee Details")

print("2. Pop Employee Details")

print("3. Display Stack")

print("4. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

empno = input("Enter employee number: ")

name = input("Enter employee name: ")

stack.append({'empno': empno, 'name': name})

elif choice == 2:

if not stack:

print("Stack is empty!")

else:

emp = stack.pop()

print(f"Popped Employee: {emp['empno']} - {emp['name']}")

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

word_to_count = input("Enter word to count: ")

count = 0

with open("w.txt", 'r') as file:

for line in file:

words = line.split()

count += words.count(word_to_count)

print(f"Occurrences of '{word_to_count}': {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:

return "Stack is empty!"

Arr = [int(x) for x in input("Enter stack elements separated by spaces: ").split()]

print("Popped value:", POP(Arr))

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

stack = [num for num in Arr if num % 5 == 0]

if stack:

print("Stack:", stack)

else:

print("No elements divisible by 5 found.")

Arr = [int(x) for x in input("Enter list elements separated by spaces: ").split()]

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 = """

CREATE TABLE IF NOT EXISTS students (

roll_no INT PRIMARY KEY,

name VARCHAR(100),

age INT,

class VARCHAR(10)

);

"""

cursor = connection.cursor()

cursor.execute(create_students_table)

connection.commit()
def add_student(connection):

roll_no = int(input("Enter Roll No: "))

name = input("Enter Name: ")

age = int(input("Enter Age: "))

class_name = input("Enter Class: ")

query = "INSERT INTO students (roll_no, name, age, class) VALUES (%s, %s, %s, %s)"

cursor = connection.cursor()

cursor.execute(query, (roll_no, name, age, class_name))

connection.commit()

print("Student added successfully.")

def display_all_students(connection):

cursor = connection.cursor()

cursor.execute("SELECT * FROM students")

rows = cursor.fetchall()

print("\nAll Student Records:")

for row in rows:

print(row)

def search_student(connection):

roll_no = int(input("Enter Roll No to search: "))

cursor = connection.cursor()

query = "SELECT * FROM students WHERE roll_no = %s"

cursor.execute(query, (roll_no,))

student = cursor.fetchone()

if student:

print("Student found:", student)

else:

print("No student found with this Roll No.")


def delete_student(connection):

roll_no = int(input("Enter Roll No to delete: "))

cursor = connection.cursor()

query = "DELETE FROM students WHERE roll_no = %s"

cursor.execute(query, (roll_no,))

connection.commit()

if cursor.rowcount > 0:

print("Student deleted successfully.")

else:

print("No student found with this Roll No.")

def update_student(connection):

roll_no = int(input("Enter Roll No to update: "))

cursor = connection.cursor()

query = "SELECT * FROM students WHERE roll_no = %s"

cursor.execute(query, (roll_no,))

student = cursor.fetchone()

if student:

print("Current Record:", student)

name = input("Enter new Name (leave blank to keep current): ")

age = input("Enter new Age (leave blank to keep current): ")

class_name = input("Enter new Class (leave blank to keep current): ")

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

SET name = %s, age = %s, class = %s

WHERE roll_no = %s

"""

cursor.execute(update_query, (name, age, class_name, roll_no))

connection.commit()

print("Student record updated successfully.")

else:

print("No student found with this Roll No.")

def main():

connection = create_connection()

create_table(connection)

while True:

print("\nMenu:")

print("1. Add Student")

print("2. Display All Students")

print("3. Search Student")

print("4. Delete Student")

print("5. Update Student")

print("6. Exit")

choice = input("Choose an option (1-6): ")

if choice == '1':

add_student(connection)

elif choice == '2':


display_all_students(connection)

elif choice == '3':

search_student(connection)

elif choice == '4':

delete_student(connection)

elif choice == '5':

update_student(connection)

elif choice == '6':

break

else:

print("Invalid choice. Please try again.")

connection.close()

if __name__ == "__main__":

main()

You might also like