0% found this document useful (0 votes)
9 views

Class_XII_Practical_list_and_file_format(2024-25)_(2026)[1]

Uploaded by

Yash Bedke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Class_XII_Practical_list_and_file_format(2024-25)_(2026)[1]

Uploaded by

Yash Bedke
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 29

Alard Public School

Practical File
Class : XII
Session : 2024-25
Roll number :
Guided by :Mrs. Swati Bante

BY: Pravin Rathod


Acknowledgement

I would like to express my heartfelt gratitude to my teacher,”


Swati “, for their guidance and support throughout the
preparation of this practical file. Their help has been invaluable
in completing this work.
I would also like to thank my classmates and friends for their
cooperation and assistance during this practical.
Lastly, I would like to thank my family for their
encouragement and support.
Thank you!
Index
Sr. No. Name Date Pg. No.
1. Write a program to calculate the power of a 18/04/2024
number (Take both numbers from user as
input)
2. Write a user defined function GenNum(x, y) 19/06/2024
to generate odd numbers between a and b
(including b)
3. Write a function that receives two numbers 24/06/2024
and generate random numbers from that
range
4. Write a program that reads a complete file 03/07/2024
line by line.
5. Write a program to display the size of a file 05/08/2024
in bytes
6 Write a python program to open the file 12/08/2024
Stu.dat and search for records with roll
numbers as 12 or 14. If found display the
records.
7 Write a python program to display the size 27/08/2024
of a file after removing EOL characters
removing white spaces and blank lines.
8 Write a Program in Python that defines and 29/08/2024
calls the user defined functions ADD() – To
accept and add data of an employee to a
CSV file ‘record.csv’.
9 Create a binary file with roll number, name 03/09/2024
and marks. Input a roll number and update
the marks.
10. A list contains following record of a
customer: 05/09/2024
[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.
11 Write a function INDEX_LIST(L), where L is the 20/09/2024
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.
12. Write Addnew(Book) and Remove(book) methods 23/09/2024
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.
13 Write functions in Python for InsertQ(Names) and 27/09/2024
for RemoveQ(Names) for performing insertion
and removal operations with a queue of List which
contains names of students.
My SQL
14. Create table and insert data. Implement all DDL 10/10/2024
commands on the table.
15. Integrate MySQL. with Python by importing the 14/10/2024
MySQL, module records of student and display all
the record.
16. Integrate MySQL with python by importing the 18/10/2024
MySQL module to search students using rollno,
name, age, class and if present in table display the
record, if not display appropriate message.
17. Integrate MYSQL with python search employee 21/10/2024
no. and update the record.
PRACTICAL NO: 1

Aim : To understand the concept of a Arithmetic operator.

Program: Writea program to calculate the power of a number (Take


both numbers from user as input)

Code:

# Python code to calculate power of a given number


num = int(input("Enter the base:"))
p = int(input("Enter the power:"))
power_cal = num ** p
print("Power of the given number is", power_cal)

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)

OUTPUT: Practical no. 2


PRACTICAL NO: 3

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)

OUTPUT: Practical no. 3


PRACTICAL NO: 4

Program: Write a program that reads a complete file line by line.

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

OUTPUT: Practical no. 4


PRACTICAL NO: 5

Program: Write a program to display the size of a file in bytes

Code:

myfile = open("poem.txt","r")
str = myfile.read()
size = len(str)
print("Size of the given file poem.txt is")
print(size,"bytes")

OUTPUT: Practical no. 5


PRACTICAL NO: 6

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

OUTPUT: Practical no. 6

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

OUTPUT: Practical no. 7

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

OUTPUT: Practical no. 8

PRACTICAL NO: 9
Program: Create a binary file with roll number, name and marks. Input a roll number
and update the marks.

Code:

#Program 1: To create Binary File


# Creating A Binary File
import pickle
stu ={}
stufile = open('Stu.dat' ,'wb')
ans = 'Y'
while ans == 'Y':
name = input("Enter student Name:")
Roll_No = int(input("Enter your roll no:"))
Marks = float(input("Enter your marks:"))
stu['Name'] = name
stu['Roll_No'] = Roll_No
stu['Marks'] = Marks
v =pickle.dump(stu , stufile)
ans = input("Want to enter more records Y or N :")
stufile.close()

#Program 2: Searching for the Record


# Searching For roll number and update the marks
import pickle
stu= {}
found = False
fin = open("Stu.dat" , 'rb+')
a = int (input("Enter the roll number of the student whose marks you want to
update:"))
b = float(input("Enter the marks to be updated:"))
try:
print("Searching in File...........")
while True:
stu = pickle.load(fin)
#print(stu)
if stu['Roll_No'] == a:
stu['Marks'] = b
pickle.dump(stu, fin)
found = True
except EOFError:
if found == False:
print("Sorry, No mathching record found......")
else:
print("Record Updated Successfully")
fin.close()
print(stu)

OUTPUT: Practical no. 2

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

# 1. Push customer details from Goa to the stack


def Push_element():
for customer in customers:
if customer[2] == 'Goa':
status.append([customer[0], customer[1]])

# 2. Pop customer details from the stack and display


def Pop_element():
if status:
while status:
print(status.pop())
else:
print("Stack Empty")

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

# Loop through the list L, checking each element


and its index
for a in range(lenght):
if L[a] != 0: # If the element is not zero, add
the index to indexList
indexList.append(a)

return indexList

L = [2,3,4,0,9,0]
call = INDEX_LIST(L)
print("Indices of all non - zero element in the list: "
, call)

OUTPUT: Practical no. 2

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

OUTPUT: Practical no. 2


PRACTICAL NO: 14
Program: Create table and insert data. Implement all DDL commands on the table.

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

3. Alter Table (e.g., adding a new column):


ALTER TABLE Customers
ADD Email VARCHAR(100);

4. Drop Table:
DROP TABLE Customers;

5. Rename Table:
ALTER TABLE Customers RENAME TO CustomerDetails;

6. ALTER TABLE Customers


MODIFY Mobile_Number VARCHAR(20);

7. Truncate Table (removes all rows but keeps the table structure):
TRUNCATE TABLE Customers;
Output Practical 14:
PRACTICAL NO: 15

Program: Integrate MySQL. with Python by importing the MySQL, module


records of student and display all the record.

Code:
1. Install MySQL connector for Python:
pip install mysql-connector-python

2. Create a MySQL database and table for students:


CREATE DATABASE School;
USE School;

CREATE TABLE Students (


Student_ID INT PRIMARY KEY,
Student_Name VARCHAR(100),
Age INT,
Grade VARCHAR(10)
);

INSERT INTO Students (Student_ID, Student_Name, Age, Grade)


VALUES (1, 'John', 18, 'A'),
(2, 'Alice', 17, 'B'),
(3, 'Bob', 19, 'A');

3. Python code to connect to MySQL, fetch, and display student records:


import mysql.connector

conn = mysql.connector.connect(host="localhost", user="your_username",


password="your_password", database="School" # replace with your database name)
cursor = conn.cursor()
cursor.execute("SELECT * FROM Students")
records = cursor.fetchall()
for record in records:
print(record)
cursor.close()
conn.close()
PRACTICAL NO: 16

Program: Integrate MySQl with python by importing the MySqlmoduleto search


students using roll no, name age class…..

Code:
import mysql.connector

def search_student(roll_no=None, name=None, age=None, student_class=None):


conn=mysql.connector.connect(host='localhost',user='root',password='12345',
database='school')
cursor = conn.cursor()
query = "SELECT * FROM students WHERE 1=1"
params = []
if roll_no:
query += " AND roll_no = %s"
params.append(roll_no)
if name:
query += " AND name = %s"
params.append(name)
if age:
query += " AND age = %s"
params.append(age)
if student_class:
query += " AND class = %s"
params.append(student_class)
cursor.execute(query, params)
result = cursor.fetchall()
if result:
print("Student Record(s) Found:")
for record in result:
print(f"Roll No: {record[0]}, Name: {record[1]}, Age: {record[2]}, Class:
{record[3]}")
else:
print("No student found matching the search criteria.")
cursor.close()
conn.close()
PRACTICAL NO: 17

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;

CREATE TABLE Employees (emp_no INT PRIMARY KEY,name


VARCHAR(100),position VARCHAR(50),salary INT);

INSERT INTO Employees (emp_no, name, position, salary)


VALUES (1, 'John', 'Manager', 50000),(2, 'Alice', 'Developer', 40000),(3, 'Bob',
'Designer', 35000);
2. Python Code to search and update employee record:
import mysql.connector

def search_and_update_employee(emp_no, new_name=None,


new_position=None, new_salary=None):

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

You might also like