practicle file class12 A
practicle file class12 A
Practical File
On
Python
Prepared By:
Name:
Class: 12 A
Name:
Class: 12 A
Certificate
This is to certify that this practical file has been completed by
_ bearing roll number
of class 12th during the session 2024-2025.
We certify that this practical work is completely original and having unique
identify.
We congratulate him for his hard work and determination in carrying out
this practical work and wish him all the success in future.
6. Write a program that repeatedly asks the user to enter product names
and prices. Store all of these in a dictionary whose keys are the
products names and whose values are the prices. When the user is
done entering products and prices, allow them to repeatedly enter a
product name and print the corresponding price or a message if the
product is not in the dictionary.
7. Insertion Sort
8. Write a function that receives two string arguments and checks
whether they are same-length strings (returns True in this case
otherwise false).
9. Write records in a binary file.
10. Read records from a binary file.
11. Search a record in a binary file.
12. Update a record in a binary file.
13. Write a program to get roll numbers, names and marks of the
students of a class and store these details in a file called “marks.txt”
also display the contents of file.
14. Write a program to write and read data from CSV file consisting Item
No, Item Name, Quantity and Price. Write a function to search for a
particular item using Item Code.
15. Write a program to implement stack.
1. Sequential search
L1=eval(input("Enter the list element"))
ele=int(input("Enter the search element"))
f=0
for a in range(0,len(L1)):
if L1[a]==ele:
f=1
break
if f==0:
print("Search element not in the list")
else:
print("Search element is in the list")
Output –
2. Bubble sort
def insertion(a,size):
for i in range(1,size):
t=a[i]
j=i-1
while j>=0 and t<a[j]:
a[j+1]=a[j]
j=j-1
else:
a[j+1]=t
print("Sorted elements are:",a)
# main program
size=int(input("Enter the size of the list"))
a=[ ]
for i in range(size):
val=int(input("enter a number"))
a.append(val)
print("You entered list as:",a)
x=insertion(a,size)
Output –
#3. Binary Search
def binarysearch(a,s,size):
f=0
first=0
last=size-1
mid=0
while first<=last and f==0:
mid=(first+last)//2
if a[mid]==s:
f=1
pos=mid+1
if a[mid]>s:
last=mid-1
if a[mid]<s:
first=mid+1
if f==1:
print("no is found at position",pos)
else:
print("no is not found")
# main program
size=int(input("Enter the size of the list"))
a=[]
for i in range(size):
val=int(input("enter a number"))
a.append(val)
print("You entered list as =",a)
a.sort()
print("After sorting the List is =",a)
s=int(input("Enter the number for search"))
binarysearch(a,s,size)
Output –
#4. Write a program that inputs two tuples tup1 and tup2 and prints True if
every element in tup1 also an element of tup2, else print False.
tup1=eval(input("Enter the first tuple squence:"))
tup2=eval(input("Enter the second tuple squence:"))
f=0
if(len(tup1)==len(tup2)):
for a in tup1:
if a not in tup2:
f=1
break
if f==1:
print("not same")
else:
print("same")
else:
print("not same")
Output –
#5. Repeatedly ask the user to enter a team name and how many games the
team has won and how many they lost. Store this information in a dictionary
where the keys are the team names and the values are lists of the form [wins,
losses].
n=int(input("how many elements you want"))
d={}
lst=[]
for a in range (n):
key=input("Enter the team name")
win=int(input("entet no of comptitions wins"))
lost=int(input("Enter the no of lost comtitions"))
d[key]=[win,lost]
if win>0:
lst+=[key]
print("now the dictionary is=")
print(d)
name=input("Enter the name of team")
print("Wining percentage",d[name][0]*100/(d[name][0]+d[name][1]))
seq=d.keys()
for a in seq:
print("Number of wins of team",a,"=",d[a][0])
print("winning records of the follwoing Team",lst)
Output –
#6. Write a program that repeatedly asks the user to enter product names and
prices. Store all of these in a dictionary whose keys are the products names
and whose values are the prices. When the user is done entering products and
prices, allow them to repeatedly enter a product name and print the
corresponding price or a message if the product is not in the dictionary.
n = int(input('Enter number of products : '))
prod = {}
for i in range(n):
p = input('Enter product name : ')
prod[p] = int(input('Enter its price : '))
q = True
while q:
p = input('Enter product for price or q to exit : ')
if p == 'q':
break
if p in prod:
print('price of', p, 'is', prod[p])
else:
print(p, 'is not here')
Output –
#7. Insertion Sort
def insertion(a,size):
for i in range(1,size):
t=a[i]
j=i-1
while j>=0 and t<a[j]:
a[j+1]=a[j]
j=j-1
else:
a[j+1]=t
print("Sorted elements are:",a)
# main program
size=int(input("Enter the size of the list"))
a=[]
for i in range(size):
val=int(input("enter a number"))
a.append(val)
print("You entered list as:",a)
x=insertion(a,size)
Output –
#8. Write a function that receives two string arguments and checks whether
they are same-length strings (returns True in this case otherwise false).
def check(a,b):
if len(a)==len(b):
return True
else:
return False
x=input("Enter first string:")
y=input("Enter the second string:")
print('length of',x, 'is equal to length of',y,'is:',check(x,y))
Output –
#9. Write records in a binary file.
import pickle
def write():
f=open("student.dat",'wb')
record=[]
while True:
rno=int(input("Enter roll no:"))
name=input("Enter Name:")
marks=int(input("Enter Marks:"))
data=[rno,name,marks]
record.append(data)
ch=input("Dou you want to enter more records?(y/n)")
if ch=='n':
break
pickle.dump(record,f)
write()
Output –
#10. Read records from a binary file.
import pickle
def read():
f=open("student.dat","rb")
while True:
try:
s=pickle.load(f)
for i in s:
print(i)
except EOFError:
break
f.close()
read()
Output –
#11. Search a record in a binary file.
import pickle
def search():
f=open("student.dat",'rb')
s=pickle.load(f)
found=0
rno=int(input("Enter the roll no whose record you want to search"))
for i in s:
if i[0]==rno:
print(i)
found=1
if found==0:
print("Record not found")
else:
print("Record found")
search()
Output –
#12. Update a record in a binary file.
import pickle
def update():
f=open("student.dat",'rb+')
s=pickle.load(f)
found=0
rno=int(input("Enter the roll no whose record you want to update"))
for i in s:
if rno==i[0]:
print("Current name:",i[1])
i[1]=input("Enter the updated name")
found=1
break
if found==0:
print("Record not found")
else:
f.seek(0)
pickle.dump(s,f)
update()
Output –
#13. Write a program to get roll numbers, names and marks of the students of
a class and store these details in a file called “marks.txt” also display the
contents of file.
def writes():
size=int(input("How many students are there in class:"))
f=open("marks.txt","w")
for i in range(size):
roll=int(input("Enter the roll no:"))
name=input("Enter the name:")
marks=float(input("Enter the marks:"))
rec=str(roll)+","+name+","+str(marks)+"\n"
f.write(rec)
f.close()
def reads():
f=open("marks.txt","r")
str1=" "
while str1:
str1=f.read()
print(str1)
f.close()
writes()
reads()
Output –
#14. Write a program to write and read data from CSV file consisting Item No,
Item Name, Quantity and Price. Write a function to search for a particular
item using Item Code.
import csv
def create( ):
f=open ("item.csv", "w", newline='')
f1=csv.writer (f)
f1.writerow (['Item No', 'Item Name', 'Quantity', 'Price'])
rec = [ ]
while True:
no=int (input("Enter Item No:"))
name=input ("Enter Item Name:")
qty=int (input ("Enter Quantity:"))
price=float(input("Enter Price:"))
record=[no, name, qty, price]
rec.append (record)
ch=input("Do you want to enter more record(y/n):")
if ch=='n':
break;
f1.writerows (rec)
def display( ):
f=open("item.csv", "r", newline='\r\n')
f1=csv.reader (f)
for i in f1:
print (i)
def search( ):
f=open ("item.csv", "r", newline='\r\n')
s=input ("Enter the Item No for search")
print("Displaying record")
f1=csv.reader (f)
next (f1)
for i in f1:
if i[0]==s:
print (i)
create( )
display( )
search( )
Output –
#Q15. Write a program to implement stack.
stack= []
choice='y'
while choice=='y':
print("1.Push")
print("2.Pop")
print("3.Display Elements of Stack")
c=int(input("Enter your choice"))
if c==1:
a=int(input("Enter the element which you want to push:"))
stack.append(a)
elif c==2:
if stack==[]:
print("Stack Empty........Underflow case......Can not delete")
else:
stack.pop()
elif c==3:
for i in range(len(stack)-1,-1,-1):
print(stack[i])
else:
print("Wrong input...")
choice=input("Do you wnat continue or not? (y/n)")
OUTPUT –
Index
SN. Name of SQL Queries/program Sign
1. CREATE TABLE Command
2. DESCRIBE Command
3. INSERT INTO Command
4. SELECT Command
5. WHERE CLAUSE
6. DISTINCT CLAUSE
7. GROUP BY CLAUSE
8. ORDER BY CLAUSE
9. Types of joins
10. Joining tables using JOIN clause of SQL SELECT
11. Describe Query with python
12. Select Query with Python
13. Execute query with new formatting style
14. Execute query with new formatting style
SQL Queries
CREATE TABLE COMMAND – This command is used to create the table.
DESCRIBE COMMAND – This command is used to see the structure of the table.
INSERT INTO COMMAND – This command is used to add the records in the table.
SELECT COMMAND – This command is used to display the records of the table.
WHERE CLAUSE – The where clause specifies the search condition used to determine the data that will appear in the
result table.
DISTINCT CLAUSE – This clause is used to remove duplicate rows in the output.
GROUP BY CLAUSE – This clause groups the rows in the result table by columns that have the same values, so that each
group is reduced to a single row.
ORDER BY CLAUSE – This clause is used to determine the order of rows in the result table.
JOINS – when we have to extract data from two or more tables, then we use join. Join is a query.
Types of Join –
Unrestricted Join –When we are joining two or more tables without any joining condition. It provides Cartesian
product.
Output –
Restricted Join –When we are joining two or more tables with a join condition than it is called restricted join. It
provides proper data.
EQUI JOINS – The join, in which column are compared for equality, is called Equi-join.
Output –
In the above output, there are two fields by the name sr from student and stu table. This type of data
redundancy can be removed by using the qualified name concepts.
Example – select student.*, stu.subject,stu.marks from student,stu
Where student.sr=stu.sr;
Output –
NATURAL JOINS –The Join in which only one of the identical columns (coming from joined tables) exists, is
called Natural Join.
Example – Select student.*, subject, marks from student, stu
Where student.sr=stu.sr;
Output –
Output –
2. CROSS JOIN –The Cartesian product of two tables is also known as CROSS JOIN. The Cross Join is a very
basic type of join that simply matches each row from one table to every row from another table.
Example – Select * from student CORSS JOIN stu;
Output –
Describe Query with python –
import mysql.connector
con=mysql.connector.connect(host='localhost',
password='123456',
user='root',
database='school')
cur=con.cursor()
cur.execute("desc student")
data=cur.fetchall()
for i in data:
print(i)
OUTPUT –
Select Query with python –
import mysql.connector
con=mysql.connector.connect(host='localhost',
password='123456',
user='root',
database='school')
cur=con.cursor()
cur.execute("select * from student")
data=cur.fetchall()
for i in data:
print(i)
OUTPUT –
Execute Query with new formatting style –
OUTPUT –
Execute Query with Old formatting style –
OUTPUT –