practicals_pythoncode24_25
practicals_pythoncode24_25
Python Program
1. User Defined functions using list
def listCopy(s):
etup=otup=()
for k in s:
if k%2==0:
etup=etup+(k,)
else:
otup=otup+(k,)
print("Tuple of even elements:",etup)
print("Tuple of odd elements:",otup)
def listUpdate():
print("List before updation=",L)
for k in range(len(L)):
if k%2!=0:
L[k]=L[k]+3
print("Updated list=:",L)
L= [12,15,5,16,2,10]
print("Original List=", L)
while True:
print("Press 1 - Copy to tuple")
print("Press 2- Update the list")
print("Press 3 - Exit")
ch=int(input("Enter your choice:"))
if ch==1:
listCopy(L)
elif ch==2:
listUpdate()
elif ch==3:
break
else:
print("Invalid choice")
2. Item Stack
Item_Stack=[]
def Push_Item():
for k in Items:
if len(k)>5:
Item_Stack.append(k)
def Pop_Item():
while True:
if Item_Stack==[]:
print("Underflow")
break
else:
print(Item_Stack.pop())
def Disp_Item():
if Item_Stack==[]:
print("None")
else:
print("Items in the stack")
print("----------------------")
n=len(Item_Stack)
for k in range(n-1,-1,-1):
print(Item_Stack[k])
Items=[]
while True:
s=input("Enter an item:")
Items.append(s)
ans=input("Want to continue:")
if ans.lower()=='n':
break
print("Items in Item list:", Items)
Push_Item()
Disp_Item()
print("------------------")
print("Items popped")
print("------------------")
Pop_Item()
3. Text file and display the occurrence of ‘this’ and ‘that’ words (both cases)
def countWords():
tt=th=0
f=open("Alpha.txt","w+")
a=input("Enter a sentence:")
f.write(a)
f.seek(0)
s=f.read()
w=s.split()
for k in w:
if k.lower()=='this':
tt+=1
elif k.lower()=="that":
th+=1
print("Occurence of this words=", tt)
print("Occurence of that words=",th)
f.close()
countWords()
4. Text file “para.txt” - display the lines starting with A and M. Display the count also.
def readLines():
with open("Para.txt") as f:
t=m=0
ln=f.readlines()
print("Lines starting with T or M are")
for j in ln:
if j[0]=='T':
print(j,end="")
t+=1
elif j[0]=='M':
print(j,end="")
m+=1
print("No.of Lines starting with 'M' =",m)
print("No.of Lines starting with 'T' =",t)
readLines()
5. Text file- copy lines starting with ‘P’ from a text file “main.txt” to another file
“new.txt”. Display the contents from new.txt.
def copyLines():
fw=open("new.txt","w+")
fr=open("main.txt")
ln=fr.readlines()
for j in ln:
if j[0].lower()=='p':
fw.write(j)
fw.seek(0)
lines=fw.readlines()
print("Contents of file new.txt")
for k in lines:
print(k,end="")
fw.close()
fr.close()
copyLines()
import pickle as p
def createFile():
with open("stud.dat","wb") as fw:
while True:
RNo=int(input("Roll Number : "))
Name=input("Student Name :")
Mark = float(input("Mark : "))
rec=[RNo,Name,Mark]
p.dump(rec,fw)
ans=input("Want to enter more records(y/n):")
if ans.lower()=='n':
break
def display():
with open("stud.dat","rb") as fr:
print("Students scored marks above 75")
while True:
try:
rec=p.load(fr)
if rec[2]>75:
print("Student Name=",rec[1],"Marks=",rec[2])
except EOFError:
break
createFile()
display()
8. CSV file “stud.csv” with fields [Rollno,Name,Marks] Search for a student with rollno
and display the details
• createCsv()- To create a file stud.csv
• Search() – To search for a record
import csv
def createCsv():
with open("Stud.csv","w",newline='') as fw:
cw=csv.writer(fw,delimiter=',')
reclist=[]
head=['Rollno','Name','Marks']
reclist.append(head)
n=int(input("Enter the limit:"))
for k in range(n):
rno=int(input("Enter rollno:"))
name=input("Enter name:")
mark=int(input("Enter marks:"))
rec=[rno,name,mark]
reclist.append(rec)
cw.writerows(reclist)
def Search():
rn=int(input("Enter rollno to search:"))
with open("Stud.csv") as fr:
cr=csv.reader(fr)
f=0
print("Student Details Searched")
next(cr)
for k in cr:
if rn==int(k[0]):
print(k)
f=1
if f==0:
print("Student record not found")
createCsv()
Search()
9. Python MySQL connectivity code to create a database BoardExam and create a table
product in the given database. Display the structure of the table.
PID INT PRIMARY KEY
PNAME VARCHAR 20
PRICE INT
QTY INT
import mysql.connector as mc
mydb=mc.connect(host="localhost",user="root",password="root@123")
cur=mydb.cursor()
cur.execute("create database boardexam")
cur.execute("use boardexam")
cur.execute("create table product(Pid int primary key,Pname varchar(15),Price int,Qty
int)")
print("Table created")
print("Table Description")
cur.execute("desc product")
for k in cur:
print(k)
mydb.close()
10) Python MySQL connectivity code to insert records into product table by accepting
values from user and display the records in the table.
import mysql.connector as mc
mydb=mc.connect(host="localhost",user="root",password="root@123",database="bo
ardexam")
cur=mydb.cursor()
n=int(input("Enter no.of records:"))
for k in range(n):
pid=int(input("Enter product id:"))
name=input("Enter product name:")
pr=int(input("Enter price:"))
qty=int(input("Enter quantity:"))
cur.execute("insert into product values(%s,'%s',%s,%s)"%(pid,name,pr,qty))
mydb.commit()
print("Records inserted")
print("Contents of product table")
cur.execute("select * from product")
for k in cur:
print(k)
mydb.close()
SQL Database: BoardExam
Table: Orders
ORDNO ITEM QTY RATE ORDDATE
1001 RICE 23 120 2023-09-10
1002 PULSES 13 120 2023-10-18
1003 WHEAT 25 110 2022-11-17
1004 GRAINS 28 65 2022-12-18
1005 CEREALS 16 55 2023-08-23
SQL
TABLE: ITEMS Database: BoardExam
TABLE: SUPPLIERS
SUPCODE SNAME CITY
S01 GET ALL INC KOLKATA
S02 EASY MARKET CORP DELHI
S03 DIGI BUSY GROUP CHENNAI
Write the SQL query for the following statements
1) Display item name & price of items whose company name starts with ‘D’.
SELECT ITEMNAME,PRICE FROM ITEMS WHERE COMPANY LIKE ‘D%’;
2) Display itemname, quantity, price and sname of items from Delhi.
SELECT ITEMNAME,QTY,PRICE,SNAME FROM ITEMS NATURAL JOIN
SUPPLIERS WHERE CITY=’DELHI’;
3) Display the details of items whose price is in the range 15000 to 25000 in ascending
order of itemname.
SELECT * FROM ITEMS WHERE PRICE BETWEEN 15000 AND 25000 ORDER
BY ITEMNAME;
4) Display itemno, itemname, sname and city of items whose supplier code is either SO2
or SO3.
SELECT ITEMNO,ITEMNAME,SNAME,CITY FROM ITEMS NATURAL JOIN
SUPPLIERS WHERE SUPCODE IN(‘S02’,’S03’);
5) Display count of each product along with supplier code.
SELECT COUNT(*), SUPCODE FROM ITEMS GROUP BY SUPCODE;