082 CS XII Practical File_copy
082 CS XII Practical File_copy
082 CS XII Practical File_copy
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.
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()
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)
def process_file(file_path):
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
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.
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")
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")
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 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 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]
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(['+', '-', '*', '/', '^'])
while stack:
postfix.append(stack.pop())
return ''.join(postfix)
def is_operator(char):
return char in '+-*/'
def prefix_to_infix(prefix):
stack = []
prefix = prefix[::-1]
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:
(vii) Delete the record from the table where credit_rating is equal to 10.
Based on the given table, write SQL queries for the following:
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
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
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()
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
update_employee_salary(1, 80000)