082 CS XII Practical File_copy

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

Practical File

Computer Science
With Python
CODE: 082
th
Class- XII
Session 2024-25
Index
Sr.
Assignment Page No. Signature
No.
Type 1: Python basic programs (15 program)
1. Write a program to print Fibonacci sequence for
n terms using recursion.
2. Write a program to find factorial of a number
using recursion.
3. Write a python program to Read a text file line
by line and display each word separated by a #.
4. Write a program to read a text file and display
the number of vowels/ consonants
uppercase/lowercase characters in the file.
5. Write a python program to remove all the lines
that contain the character 'a' in a file and write
it to another file.
6. Write a program to 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.
7. Write a python program to create a binary file
with roll number, name and marks. Input a roll
number and update the marks.
8. Write a program to create dice-roll game with
random module.
9. Write a program to implement stack using list.

10. Write a python program to Create a CSV file by


entering user-id and password, read and search
the password for given user-id.
11. Write a python program to create phonebook
application.
12. Write a program to perform all operations of
Inventory management system.
13. Write a program to convert prefix to postfix
(Stack application)
14. Write a program to convert infix to postfix
(Stack application)
15. Write a program to convert prefix to infix (Stack
application)
Type 2: Database Management (5 sets)
16. DBMS Set-1

17. DBMS Set-2

18. DBMS Set-3

19. DBMS Set-4

20. DBMS Set-5

Type 3: Python-SQL Connectivity (5 Program)


21. Write a program to create connection with
mysql server.
22. Write a program to create table into database
using python.

23. Write a program to insert data into table using


python.
24. Write a program to fetch record from the table
using python.
25. Write a program to update records in table
using python.
Practical- 1
Program: Write a program to print Fibonacci sequence for n terms using
recursion.

def fibonacci(n):
if n <= 0:
return "Input must be a positive integer."
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)

def print_fibonacci_sequence(n):
if n <= 0:
print("Input must be a positive integer.")
else:
for i in range(1, n + 1):
print(fibonacci(i), end=' ')
print()

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


print_fibonacci_sequence(n)
Practical- 2
Program: Write a program to find factorial of a number using recursion.

def factorial(n):
if n < 0:
return "Input must be a non-negative integer."
elif n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)

n = int(input("Enter a non-negative integer: "))


result = factorial(n)
print("The factorial of ”,n,“ is ”,result)
Practical- 3
Program: Write a python program to Read a text file line by line and display each
word separated by a #.

def process_file(file_path):

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

for line in file:

words = line.split()

print('#'.join(words))

file_path = 'example.txt'

process_file(file_path)
Practical- 4
Program: Write a program to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.

def count_characters(file_path):
vowels = "aeiouAEIOU"
num_vowels = 0
num_consonants = 0
num_uppercase = 0
num_lowercase = 0

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


for line in file:
for char in line:
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("Number of vowels: ",num_vowels)


print("Number of consonants: ",num_consonants)
print("Number of uppercase characters: ",num_uppercase)
print("Number of lowercase characters: ",num_lowercase)

file_path = 'example.txt'
count_characters(file_path)
Practical- 5
Program: write a python program to remove all the lines that contain the
character 'a' in a file and write it to another file.

def remove_lines_with_a(input_file_path, output_file_path):


with open(input_file_path, 'r') as infile:
lines = infile.readlines()

remaining_lines = [line for line in lines if 'a' not in line.lower()]


line_with_a = [line for line in lines if 'a' in line.lower()]

with open(output_file_path, 'w') as outfile:


outfile.writelines(line_with_a)

with open(input_file_path, 'w') as infile:


infile.writelines(remaining_lines)

print("Lines without 'a' have been written to: ",input_file_path)


print("Lines with 'a' have been written to : ",output_file_path)

input_file_path = 'input.txt'
output_file_path = 'output.txt'
remove_lines_with_a(input_file_path, output_file_path)
Practical- 6
Program: write a program to 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 set_data():
rollno = int(input('Enter roll number: '))
name = input('Enter name: ')
#create a dictionary
student = {}
student['rollno'] = rollno
student['name'] = name
return student

def display_data(student):
print('Name:', student['name'])
print()

def write_record():
outfile = open('student.dat', 'ab')
pickle.dump(set_data(), outfile)
outfile.close()

def search_record():
infile = open('student.dat', 'rb')
rollno = int(input('Enter rollno to search: '))
flag = False
while True:
try:
student = pickle.load(infile)
if student['rollno'] == rollno:
display_data(student)
flag = True
break

except EOFError:
break

if flag == False:
print('Record not Found')
print()
infile.close()

def show_choices():
print('Menu')
print('1. Add Record')
print('2. Search a Record')
print('3. Exit')
while(True):
show_choices()
choice = input('Enter choice(1-3): ')
print()
if choice == '1':
write_record()
elif choice == '2':
search_record()
elif choice == '3':
break
else:
print('Invalid input')
Practical- 7
Program: Write a python program to create a binary file with roll number, name
and marks. Input a roll number and update the marks.

import pickle
def create_binary_file(file_path, data):
with open(file_path, 'wb') as file:
pickle.dump(data, file)
print(f"Data has been written to {file_path}")
def update_marks(file_path, roll_number, new_marks):
try:
with open(file_path, 'rb') as file:
data = pickle.load(file)
updated = False
for student in data:
if student['roll_number'] == roll_number:
student['marks'] = new_marks
updated = True
break
if updated:
with open(file_path, 'wb') as file:
pickle.dump(data, file)
print(f"Marks for roll number {roll_number} have been updated to
{new_marks}.")
else:
print(f"Roll number {roll_number} not found.")
except FileNotFoundError:
print(f"The file {file_path} was not found.")
except Exception as e:
print(f"An error occurred: {e}")
def display_data(file_path):
try:
with open(file_path, 'rb') as file:
data = pickle.load(file)
for student in data:
print(f"Roll Number: {student['roll_number']}, Name: {student['name']},
Marks: {student['marks']}")
except FileNotFoundError:
print(f"The file {file_path} was not found.")
except Exception as e:
print(f"An error occurred: {e}")
data = [
{'roll_number': 1, 'name': 'Alice', 'marks': 85},
{'roll_number': 2, 'name': 'Bob', 'marks': 90},
{'roll_number': 3, 'name': 'Charlie', 'marks': 95},
]
file_path = 'students.dat'
create_binary_file(file_path, data)
print("Current data in the file:")
display_data(file_path)
roll_number_to_update = int(input("Enter the roll number to update: "))
new_marks = int(input("Enter the new marks: "))
update_marks(file_path, roll_number_to_update, new_marks)
print("Updated data")
display_data(file_path)
Practical- 8
Program: write a program to create dice-roll game with random module.
import random
def roll_dice():
return random.randint(1, 6)

player2 = ["Leo","Jack","Martin","Maria","Veda","Singham"]

while True:
print("******** Menu ********")
print("1. Your Turn")
print("0. Exit")

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


if choice == 1:
name = input("Enter your name: ")
p1 = roll_dice()
print(name," : ",p1)
key = roll_dice() - 1
p2 = roll_dice()
print(player2[key]," : ",p2)
if p1 == p2:
print("Draw!!")
elif p1>p2:
print(name," has won the match.")
else:
print(player2[key]," has won the match.")
elif choice == 0:
break
else:
print("you have not entered right option. Restart .........")
Practical- 9
Program: Write a program to implement stack using list.
stack = []
def isEmpty():
if len(stack) == 0:
print("Stack is Empty.")
else:
print("Stack is not Empty.")
def push():
val = input("Enter the Value to push: ")
stack.append(val)
print(val," pushed !!")

def pop():
try:
val = stack.pop()
print(val, " popped !!")
except IndexError:
print("This operation can not be perfromed now because stack is already
emplty.")

def peek():
top = len(stack) - 1
peek = stack[top]
print(peek, " is the peek value.")

def size():
print("The size of the stack: ",len(stack))

def display():
if len(stack) != 0:
for i in stack:
print(i,end=">>")
else:
print("Stack is Empty.")
while True:
print("\n *** *** *** Stack Implementaion *** *** *** \n")
print("1. Push Element")
print("2. Pop Element")
print("3. Is Empty")
print("4. Peek Element")
print("5. Size of Stack")
print("6. Display Stack")
print("0. Exit")

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


if choice == 1:
push()
elif choice == 2:
pop()
elif choice == 3:
isEmpty()
elif choice == 4:
peek()
elif choice == 5:
size()
elif choice == 6:
display()
elif choice == 0:
break
else:
print("Restart........")
Practical- 10
Program: Write a python program to create a CSV file by entering user-id and
password, read and search the password for given user-id.

import csv
def create_csv_file(file_path):
with open(file_path, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["user_id", "password"])

while True:
user_id = input("Enter user ID (or press 0 to stop): ")
if user_id.lower() == '0':
break
password = input("Enter password: ")
writer.writerow([user_id, password])
print(f"User ID {user_id} and password added to {file_path}.")

def search_password(file_path):
search_user_id = input("Enter the user ID to search for the password: ")
with open(file_path, 'r') as file:
reader = csv.reader(file)
next(reader) # Skip the header row
for row in reader:
if row[0] == search_user_id:
pw= row[1]
print("Password for user ID ",search_user_id," : ",pw)
return "User ID not found."

file_path = 'users.csv'
while True:
print("*** *** *** Menu *** *** ***")
print("1. Add Records")
print("2. Find Password")
print("3. exit")
ch = int(input("Enter your choice: "))
if ch == 1:
create_csv_file(file_path)
elif ch == 2:
search_password(file_path)
elif ch == 3:
break
else:
print("Restart .....")
Practical- 11
Program: Write a python program to create phonebook application.

def add_contact(phonebook, name, phone_number):


phonebook[name] = phone_number
print("Contact ",name," added with phone number ",phone_number)

def delete_contact(phonebook, name):


if name in phonebook:
del phonebook[name]
print("Contact ",name," deleted.")
else:
print("Contact ",name," not found.")

def update_contact(phonebook, name, new_phone_number):


if name in phonebook:
phonebook[name] = new_phone_number
print("Contact ",name," updated with new phone number
",new_phone_number)
else:
print("Contact ",name," not found.")

def search_contact(phonebook, name):


return phonebook.get(name, "Contact not found.")

def display_contacts(phonebook):
if phonebook:
for name, number in phonebook.items():
print(name," : ",number)
else:
print("No contacts found.")
# Example usage:
phonebook = {}
while True:
print("\nPhonebook Menu:")
print("1. Add Contact")
print("2. Delete Contact")
print("3. Update Contact")
print("4. Search Contact")
print("5. Display All Contacts")
print("6. Exit")
choice = input("Enter your choice: ")

if choice == '1':
name = input("Enter name: ")
phone_number = input("Enter phone number: ")
add_contact(phonebook, name, phone_number)
elif choice == '2':
name = input("Enter name to delete: ")
delete_contact(phonebook, name)
elif choice == '3':
name = input("Enter name to update: ")
new_phone_number = input("Enter new phone number: ")
update_contact(phonebook, name, new_phone_number)
elif choice == '4':
name = input("Enter name to search: ")
print(search_contact(phonebook, name))
elif choice == '5':
display_contacts(phonebook)
elif choice == '6':
break
else:
print("Invalid choice, please try again.")
Practical- 12
Program: Write a program to perform all operations of Inventory management
system.
def add_item(inventory, item_name, quantity, price):
if item_name in inventory:
inventory[item_name]['quantity'] += quantity
inventory[item_name]['price'] = price
else:
inventory[item_name] = {'quantity': quantity, 'price': price}
print("Item ",item_name," added.")

def remove_item(inventory, item_name):


if item_name in inventory:
del inventory[item_name]
print("Item ",item_name," removed.")
else:
print("Item ",item_name," not found.")

def update_item(inventory, item_name, quantity, price):


if item_name in inventory:
inventory[item_name]['quantity'] = quantity
inventory[item_name]['price'] = price
print("Item ",item_name," updated.")
else:
print("Item ",item_name," not found.")

def display_inventory(inventory):
if inventory:
for item_name, details in inventory.items():
print(item_name," : Quantity= ",details['quantity']," Price=",details['price'])
else:
print("Inventory is empty.")

# Example usage:
inventory = {}
while True:
print("\nInventory Management Menu:")
print("1. Add Item")
print("2. Remove Item")
print("3. Update Item")
print("4. Display Inventory")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
item_name = input("Enter item name: ")
quantity = int(input("Enter quantity: "))
price = float(input("Enter price: "))
add_item(inventory, item_name, quantity, price)
elif choice == '2':
item_name = input("Enter item name to remove: ")
remove_item(inventory, item_name)
elif choice == '3':
item_name = input("Enter item name to update: ")
quantity = int(input("Enter new quantity: "))
price = float(input("Enter new price: "))
update_item(inventory, item_name, quantity, price)
elif choice == '4':
display_inventory(inventory)
elif choice == '5':
break
else:
print("Invalid choice, please try again.")
Practical- 13
Program: Write a program to convert prefix to postfix (Stack application)

def is_operator(char):
return char in '+-*/^'

def prefix_to_postfix(prefix):
stack = []
prefix = prefix[::-1]

for char in prefix:


if char.isalnum():
stack.append(char)
elif is_operator(char):
operand1 = stack.pop()
operand2 = stack.pop()
postfix_expression = operand1 + operand2 + char
stack.append(postfix_expression)

return stack.pop()

prefix_expression = "*+AB-CD"
postfix_expression = prefix_to_postfix(prefix_expression)
print(f"Prefix Expression: {prefix_expression}")
print(f"Postfix Expression: {postfix_expression}")
Practical- 14
Program: Write a program to convert infix to postfix (Stack application).

def precedence(op):
if op == '+' or op == '-':
return 1
if op == '*' or op == '/':
return 2
if op == '^':
return 3
return 0

def infix_to_postfix(infix):
stack = []
postfix = []
operators = set(['+', '-', '*', '/', '^'])

for char in infix:


if char.isalnum():
postfix.append(char)
elif char == '(':
stack.append(char)
elif char == ')':
while stack and stack[-1] != '(':
postfix.append(stack.pop())
stack.pop()
elif char in operators:
while stack and precedence(stack[-1]) >= precedence(char):
postfix.append(stack.pop())
stack.append(char)

while stack:
postfix.append(stack.pop())

return ''.join(postfix)

infix_expression = "A + B * C - D / E"


postfix_expression = infix_to_postfix(infix_expression)
print(f"Infix Expression: {infix_expression}")
print(f"Postfix Expression: {postfix_expression}")
Practical- 15
Program: Write a program to convert prefix to infix (Stack application).

def is_operator(char):
return char in '+-*/'

def prefix_to_infix(prefix):
stack = []
prefix = prefix[::-1]

for char in prefix:


if is_operator(char):
operand1 = stack.pop()
operand2 = stack.pop()
infix_expression = f"({operand1} {char} {operand2})"
stack.append(infix_expression)
else:
stack.append(char)

return stack.pop()

prefix_expression = "*+AB-CD"
infix_expression = prefix_to_infix(prefix_expression)
print("Prefix Expression: ",prefix_expression)
print(f"Infix Expression: ",infix_expression)
Practical- 16
Set 1: Perform the CRUD Operation with the following data.
Table: Customer
C_ID C_NAME CITY CREDIT_RATING
101 Jones New York 20
102 Martinez London 15
103 Leo Paris 15
104 Jack London 20
105 Stark New York 10
106 Mark Paris 15
107 Mooc London 15
108 Maxe London 15
109 Maria Paris 10
110 Alexa New York 15
Write the SQL Queries for the following:

(i) Create the above table.

Query: create table customer(


-> c_id int(4),
-> c_name varchar(10),
-> city varchar(10),
-> credit_rating int(4)
-> );
(ii) Insert data to the table.
Query: insert into customer values
-> (101,'jones','new york',20),
-> (102,'Martinez','london',15),
-> (103,'Leo','paris',15),
-> (104,'Jack','london',20),
-> (105,'Stark','new york',10),
-> (106,'Mark','paris',15),
-> (107,'Mooc','london',15),
-> (108,'Maxe','london',15),
-> (109,'Maria','paris',10),
-> (110,'Alexa','new york',15);
(iii) Display the structure of table.
Query: desc customer;

(iv) Display all the data of table.

Query: Select * from customer.

(v) Display only c_name and credit_rating.

Query: select c_name,credit_rating from customer;

(vi) Update the credit_rating of Leo from 15 to 18.

Query: update customer set credit_rating = 18 where c_name = ‘Leo’;

(vii) Delete the record from the table where credit_rating is equal to 10.

Query: delete from customer where credit_rating = 10;


Practical- 17
Set 2: Consider the table Personal given below:
Table: Personal
P_ID Name Desig Salary Allowance
P01 Rohit Manager 89000 4800
P02 Kashish Clerk NULL 1600
P03 Mahesh Superviser 48000 NULL
P04 Salil Clerk 31000 1900
P05 Ravina Superviser NULL 2100

Based on the given table, write SQL queries for the following:

(i) Increase the salary by 5% of personals whose allowance is known.


Query: update personal set
-> salary = coalesce(salary,0)+coalesce(allowance,0)*0.05;
(ii) Display Name and Total Salary (sum of Salary and Allowance) of all
personals. The column heading ‘Total Salary’ should also be displayed.
Query: select name,coalesce(salary,0)+coalesce(allowance,0) as "Total Salary"
from personal;
(iii) Delete the record of personals who have salary greater than 25000
Query: delete from personal where salary>25000;
Practical- 18
Set 3: Consider the tables PRODUCT and BRAND given below:
Table: PRODUCT
PCode PName Price Rating BID
P01 Shampoo 120 6 M03
P02 Toothpaste 54 8 M02
P03 Soap 25 7 M03
P04 Toothpaste 65 4 M04
P05 Soap 38 5 M05
P06 Shampoo 245 6 M05

Table: BRAND
BID BName
M02 Dant Kanti
M03 Medimix
M04 Pepsodent
M05 Dove
Write SQL queries for the following:
(i) Display product name and brand name from the tables PRODUCT and
BRAND.
Query: select pname,bname from product inner join brand on product.bid =
brand.bid;
(ii) Display the structure of the table PRODUCT.
Query: desc product;
(iii) Display the average rating of Medimix and Dove brands
Query: select bname,avg(rating) as "Average rating" from product inner join
brand on product.bid = brand.bid group by bname;
(iv) Display the name, price, and rating of products in descending order of
rating.
Query: select pname,price,rating from product order by rating desc;
Practical- 19
Set 4: Consider the following table student.
Student_ID Name Class Gender
101 Anuj 11 M
102 Anu 11 F
103 Kanika 12 F
104 Manoj 12 M
105 Rishabh 12 M
106 Yash 12 M
107 Parv 12 M
108 Shashank 11 M
109 Deepanshi 11 F
110 Mayank 11 M
Write the SQL Queries for the following:

(i) Find the list of the student whose name starts with ‘M’.
Query: select name from student where name like 'm%';
(ii) Find the list of the all Male Students.
Query: select name from student where gender='m';
(iii) Find the list of the all students of class 12.
Query: select name from student where class = 12;
(iv) Find the name of the students whose name ends with ‘j’.
Query: select name from student where name like '%j';
(iv) Find the name of that student whose name starts with ‘A’ and Gender is F.
Query: select name from student where name like 'a%' and gender = 'f';
Practical- 20
Set 5: Consider the following stu_marks table.
Table: stu_marks
Stu_ID Name Sub1 Sub2 Sub3 Sub4 Sub5 Sub6
1 Raj 50 55 80 69 78 84
2 Rahul 80 30 85 63 55 48
3 Yatharth 91 92 90 95 97 96
4 Yug 32 75 77 79 80 86

Write the SQL Queries for the following:


(i) Display student name and total marks.
Query: select name,sub1+sub2+sub3+sub4+sub5+sub6 as "Total marks" from
stu_marks;
(ii) Display student name and percentage.
Query: select name,(sub1+sub2+sub3+sub4+sub5+sub6)/6 as percentage from
stu_marks;
(iii) Count the student whose name start with ‘R’.
Query: select count(name) from stu_marks where name like 'r%';
(iv) Display the name of that student who scored maximum marks in sub4.
Query: select name,max(sub4) from stu_marks;
(v) Display the name of that student who scored minimum marks in sub2.
Query: select name,min(sub2) from stu_marks;
Practical- 21
Program: Write a program to create connection with mysql server.
import mysql.connector
from mysql.connector import Error

def connect_to_database():
try:
connection = mysql.connector.connect(
host='localhost',
database='vtdb',
user='root',
password=''
)
if connection.is_connected():
print("Connected to MySQL database")
db_info = connection.get_server_info()
print("MySQL server version:", db_info)

except Error as e:
print("Error while connecting to MySQL", e)

finally:
if connection.is_connected():
connection.close()
print("MySQL connection is closed")

connect_to_database()
Practical- 22
Program: Write a program to create table into database using python.
import mysql.connector
from mysql.connector import Error

def create_table():
try:
connection = mysql.connector.connect(
host='localhost',
database='vtdb',
user='root',
password=''
)

cursor = connection.cursor()
cursor.execute("""
CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
salary DECIMAL(10, 2) NOT NULL,
department VARCHAR(255) NOT NULL,
position VARCHAR(255) NOT NULL,
hire_date DATE NOT NULL
)
""")

connection.commit()
print("Table created successfully")

except Error as e:
print("Error while creating table", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")

create_table()
Practical-23
Program: write a program to insert data into table using python.
import mysql.connector
from mysql.connector import Error

def insert_employee(name, salary, department, position, hire_date):


try:
connection = mysql.connector.connect(
host='localhost',
database='vtdb',
user='root',
password=''
)
cursor = connection.cursor()
insert_query = """
INSERT INTO employees (name, salary, department, position, hire_date)
VALUES (%s, %s, %s, %s, %s)
"""
record = (name, salary, department, position, hire_date)
cursor.execute(insert_query, record)
connection.commit()
print("Record inserted successfully")
except Error as e:
print("Error while inserting record", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")

insert_employee('John Doe', 75000, 'IT', 'Developer', '2023-01-15')


Program- 24
Program: write a program to fetch record from the table using python.

import mysql.connector
from mysql.connector import Error

def fetch_employees():
try:
connection = mysql.connector.connect(
host='localhost',
database='vtdb',
user='root',
password=''
)
cursor = connection.cursor()
cursor.execute("SELECT * FROM employees")
rows = cursor.fetchall()

for row in rows:


print(f"ID: {row[0]}, Name: {row[1]}, Salary: {row[2]}, Department: {row[3]},
Position: {row[4]}, Hire Date: {row[5]}")

except Error as e:
print("Error while fetching data", e)

finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")

fetch_employees()
Practical- 25
Program: write a program to update records in table using python.
import mysql.connector
from mysql.connector import Error

def update_employee_salary(employee_id, new_salary):


try:
connection = mysql.connector.connect(
host='localhost',
database='vtdb',
user='root',
password=''
)
cursor = connection.cursor()
update_query = """
UPDATE employees
SET salary = %s
WHERE id = %s
"""
cursor.execute(update_query, (new_salary, employee_id))
connection.commit()
print("Record updated successfully")
except Error as e:
print("Error while updating record", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")

update_employee_salary(1, 80000)

You might also like