Class_XII_Practical_list_and_file_format(2024-25)_(2026)[1]
Class_XII_Practical_list_and_file_format(2024-25)_(2026)[1]
Practical File
Class : XII
Session : 2024-25
Roll number :
Guided by :Mrs. Swati Bante
Code:
OUTPUT: Practical 1
PRACTICAL NO: 2
Aim : To understand how to generate odd numbers within a given range using a
user-defined function in Python.
Program : Write a user defined function GenNum(x, y) to generate odd numbers between
a and b (including b)
Code:
def GenNum(a,b):
for num i range(a,b):
if num%2!=0:
print(num)
a = int(input("Enter the beginning number :"))
b = int(input("Enter the ending number :"))
GenNum(a,b)
Program: Write a function that receives two numbers and generate random numbers
from that range
Code:
import random
num1 = float(input("Enter beginning number :"))
num2 = float(input("Enter ending number :"))
r = random.uniform(num1,num2)
print(r)
Code:
myfile = open("poem.txt","r")
str = " " #initially storing a aspace (any non-None value)
while str:
str = myfile.readline()
print(str,end=" ")
myfile.close()
Code:
myfile = open("poem.txt","r")
str = myfile.read()
size = len(str)
print("Size of the given file poem.txt is")
print(size,"bytes")
Program: Write a python program to open the file Stu.dat and search for records with
roll numbers as 12 or 14. If found display the records.
Code:
import pickle
stu = {}
found = False
try:
with open("Stu.dat", "rb") as fin:
print("Searching in File Stu.dat...")
while True:
try:
stu = pickle.load(fin)
if stu["Rollno"] in searchkeys:
print(stu)
found = True
except EOFError:
break
except FileNotFoundError:
print("The file 'Stu.dat' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
if not found:
print("No matching student records found.")
PRACTICAL NO: 7
Program: Write a python program to display the size of a file after removing EOL
characters removing white spaces and blank lines.
Code:
myfile = open("poem.txt","r")
str = " "
size = 0
tsize = 0
while str1:
str1 = myfile.readline()
tsize = tsize+len(str1)
size = size+len(str.strip())
print("Size of file after removing all EOL characters&blank lines:",size)
print("The TOTAL size m,of the file:",tsize)
myfile.close()
PRACTICAL NO: 8
Program: Write a Program in Python that defines and calls the user defined functions
ADD() – To accept and add data of an employee to a CSV file ‘record.csv’
Code:
import csv
def ADD():
fout = open("record.csv","a",newline = "\n")
wr = csv.writer(fout)
empid = int(input("Enter Employee id :: "))
name = input("Enter name :")
moblie = int(input("Enter moblie number :: "))
lst = [empid,name,mobile]
wr.writerow(lst)
fout.close
ADD()
PRACTICAL NO: 9
Program: Create a binary file with roll number, name and marks. Input a roll number
and update the marks.
Code:
PRACTICAL NO: 10
Program: A list contains following record of a customer:
[Customer_name ,Mobile_number, City]
Write the following user defined functions to perform given operations on the stack named
status:
1.Push_element() – To Push an object containing name and Phone number of customers
who live in Goa to the stack.
2.Pop_element() – To Pop the objects from the stack and display them. Also display
“Stack Empty” when there are no elements in the stack.
Code:
status = []
# List of customers with name, phone number, and city
customers = [
['John', '1234567890', 'Goa'],
['Alice', '9876543210', 'Mumbai'],
['Bob', '1122334455', 'Goa'],
['Eve', '6677889900', 'Delhi']
]
# Example usage
Push_element()
Pop_element()
OUTPUT: Practical no. 2
PRACTICAL NO: 11
Program: Write a function INDEX_LIST(L), where L is the list of elements passed as
argument to the function. The function returns another list named ‘indexList’ that stores
the indices of all Non-Zero Elements of L.
Code:
def INDEX_LIST(L):
# Initialize an empty list to store the indices of
non-zero elements
indexList = []
lenght = len(L)
return indexList
L = [2,3,4,0,9,0]
call = INDEX_LIST(L)
print("Indices of all non - zero element in the list: "
, call)
PRACTICAL NO: 12
Program: Write Addnew(Book) and Remove(book) methods in Python to Add a new
Book and Remove a Book from a List of Books, considering them to act as Push and Pop
operations of the data structure Stack.
Code:
def Addnew(Book,Bname):
Book.append(Bname)
top = len(Book)-1
def Remove(Book):
Book.pop()
if Book == []:
print("underflow")
else:
top = len(Book)-1
Book = []
top = None
while True:
print("Stack operations")
print("1.Add new Book")
print("2.Delete a Book")
print("3.Print Book List")
print("4.Quit")
ch = int(input("Enter your choice :"))
if ch == 1:
Bname = input("Enter the Book name to be added")
Addnew(Book,Bname)
elif ch == 2:
Remove(Block)
elif ch == 3:
print(Block)
elif ch == 4:
break
else:
print("Invalid memory")
OUTPUT: Practical no. 2
PRACTICAL NO: 13
Program: Write functions in Python for InsertQ(Names) and for RemoveQ(Names) for
performing insertion and removal operations with a queue of List which contains names of
students.
Code:
def InsertQ(Names):
name = input("Enter the name of the student to insert: ")
Names.append(name)
print(f"'{name}' has been added to the queue.")
def RemoveQ(Names):
if len(Names) == 0:
print("Queue is empty; UNDERFLOW!")
else:
removed_name = Names.pop(0) # Remove the first element
print(f"'{removed_name}' has been removed from the queue.")
queue = [] # Initialize an empty queue
while True:
print("\nQueue Operations:")
print("1. Insert a student")
print("2. Remove a student")
print("3. Display queue")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == "1":
InsertQ(queue)
elif choice == "2":
RemoveQ(queue)
elif choice == "3":
print("Current queue:", queue)
elif choice == "4":
print("Exiting the program.")
Code:
1.Create Table:
CREATE TABLE Customers (Customer_ID INT PRIMARY KEY,Customer_Name
VARCHAR(100),Mobile_Number VARCHAR(15),City VARCHAR(50));
2. Insert Data:
INSERT INTO Customers (Customer_ID, Customer_Name, Mobile_Number, City)
VALUES (1, 'John', '1234567890', 'Goa'),(2, 'Alice', '9876543210', 'Mumbai'),(3, 'Bob',
'1122334455', 'Goa'),(4, 'Eve', '6677889900', 'Delhi');
4. Drop Table:
DROP TABLE Customers;
5. Rename Table:
ALTER TABLE Customers RENAME TO CustomerDetails;
7. Truncate Table (removes all rows but keeps the table structure):
TRUNCATE TABLE Customers;
Output Practical 14:
PRACTICAL NO: 15
Code:
1. Install MySQL connector for Python:
pip install mysql-connector-python
Code:
import mysql.connector
Program: Integrate MYSQL with python search employee no. and update the
record.
Code:
1. Create the database and table for employees:
CREATE DATABASE Company;
USE Company;
conn=mysql.connector.connect(host='localhost',user='root',password='1234
5',database='Company')
cursor = conn.cursor()
cursor.execute("SELECT * FROM Employees WHERE emp_no =
%s", (emp_no,))
employee = cursor.fetchone()
if employee:
if new_name:
cursor.execute("UPDATE Employees SET name = %s WHERE
emp_no = %s", (new_name, emp_no))
if new_position:
cursor.execute("UPDATE Employees SET position = %s WHERE
emp_no = %s", (new_position, emp_no))
if new_salary:
cursor.execute("UPDATE Employees SET salary = %s
WHERE emp_no = %s", (new_salary, emp_no))
conn.commit()
print(f"Employee record updated: {emp_no}")
else:
print("Employee not found!")
cursor.close()
conn.close()
# Example usage:
search_and_update_employee(2, new_name="Alicia",new_position="Senior
Developer", new_salary=45000)
OUTPUT (Practical 17) :