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

practicals_pythoncode24_25

The document outlines various Python programming tasks related to data structures, file handling, and database operations. It includes user-defined functions for list manipulation, stack operations, word counting in text files, CSV file operations, and MySQL database connectivity for creating and managing records. Each task is demonstrated with code snippets and explanations for clarity.

Uploaded by

devak k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

practicals_pythoncode24_25

The document outlines various Python programming tasks related to data structures, file handling, and database operations. It includes user-defined functions for list manipulation, stack operations, word counting in text files, CSV file operations, and MySQL database connectivity for creating and managing records. Each task is demonstrated with code snippets and explanations for clarity.

Uploaded by

devak k
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

PRACTICAL CODE-2024 -25

COMPUTER SCIENCE (083)

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

6) Binary file “stud.dat” with structure [RollNo, Name, Mark]


• createFile() to input data to the file “stud.dat”.
• display() to display the details of the student who scored marks above 75

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

7. CSV file “book.csv” with fields [BNo,Bname,Author,Price]


• Accept()- To create the csv file book.csv
• Display()- To read and display contents read and display the contents from the file.
import csv
def Accept():
fw=open("Book.csv","w",newline='')
cw=csv.writer(fw,delimiter=',')
head=['BNo','BName','Author','Price']
cw.writerow(head)
n=int(input("Enter the limit:"))
for k in range(n):
bno=int(input("Enter Book No:"))
bname=input("Enter Book name:")
aut=input("Enter Author name:")
pr=int(input("enter price:"))
rec=[bno,bname,aut,pr]
cw.writerow(rec)
fw.close()
def Display():
fr=open("Book.csv")
cr=csv.reader(fr)
print("Book Details")
for k in cr:
print(k)
fr.close()
Accept()
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

Write the SQL query for the following statements


1. Display order number, item name, rate and order date of orders whose rate is
greater than 100.
SELECT ORDNO,ITEM,RATE,ORDDATE FROM ORDERS WHERE
RATE>100;
2. Display the item name, quantity and rate of items that ends with ‘s’ in
ascending order of name.
SELECT ITEM,QTY,RATE FROM ORDERS WHERE ITEM LIKE ‘%S’
ORDER BY ITEM;
3. Increment the quantity of each order by 5.
UPDATE ORDERS SET QTY=QTY+5;
4. Display the item name and Amount(Qty * Rate) of all orders.
SELECT ITEM, QTY*RATE AS AMOUNT FROM ORDERS;
5. Display item name, rate and order date of all items ordered between 1st
December 2022 and 30th September 2023
SELECT ITEM,RATE,ORDDATE FROM ORDERS WHERE ORDDATE
BETWEEN ‘2022-12-01’ AND ‘2023-09-30’;

SQL
TABLE: ITEMS Database: BoardExam

ITEMNO ITEMNAME QTY PRICE COMPANY SUPCODE


101 DIGITAL CAMERA 120 18000 RENIX S01
14X
102 DIGITAL PAD 11i 100 22000 DIGI POP S02
103 PEN DRIVE 16 GB 500 1100 STOREKING S01
104 LED SCREEN 32 70 28000 DISPEXPERTS S02
105 CAR GPS SYSTEM 60 12000 MOVEON S03

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;

You might also like