0% found this document useful (0 votes)
8 views38 pages

Python & MySQL Practical File 2024-25

Uploaded by

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

Python & MySQL Practical File 2024-25

Uploaded by

jevika.987
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

GLT Saraswati Bal Mandir Sr. Sec.

School,
Nehru Nagar, New Delhi - 110065

Session: 2024-2025
Computer Science
Code (083)
Practical File

Submitted By:
Name: Jevika
Class: 12th B
Roll No.: 15
INDEX
PYTHON PROGRAMS
SNO. PYTHON PROGRAM REMARK
1. Read a text file line by line and display each word separated by #.

2. Read a text file and display the number of


vowels/consonants/uppercase/lowercase characters in the file.

3. Remove all the lines that contain the character ‘a’ in a file and
write it to another file.

4. Create a Binary file with name and roll number. Search for a given
roll number and display the name, if not found display appropriate
message.

5. Write a Random number generator that generates random numbers


between 1 and 6 (simulates a dice ).

6. Create a binary file with roll number , name and marks. Input a roll
number and update the marks .

7. Write a python program to implement a stack using list.

8. Create a CSV file by entering user-id and password, read and


search the password for given user id.
9. Write a method in Python to read lines from a text file
“[Link]” and display those lines start with the alphabet ‘K’.

10. Write a function in python POP(Arr) , where Arr is a Stack


implemented by a list of number . This function returns the value
deleted from the Stack

11. Write a user defined function CreateFile() to input data for record
and add to ‘[Link]’

12. Program to input a string and count the number of uppercase and
lowercase letters.
13. Program to find maximum , minimum , and mean value from the
list
14. Write a Python function to sum all the items in a list .

15. Python program to search record for given students name from
csv file .
MY SQL COMMANDS
SNO. COMMAND REMARK
1. To add records in store table

2. To display names of stores along with


SalesAmount of those stores that have‘fashion’
anywhere in their store names.

3. To display names of the cities and the total


amount of sales on the basis of City

4. Add a new record with following data:


(‘S107’,’Mymart’,’Rajivchowk’,’Delhi’,9,2015-09-07,9000)

5. Increase sales amount by 4000 whose city is


Delhi
6. Remove records of those whose store id is S103
.

CONNECTIVITY( INTERFACE WITH PYTHON )


SNO. PROGRAM REMARK
1. To insert a new record into table student in MYSQL
using Python interface.

2. To fetch all records from student table using


Python interface .

3. To delete records from the table student using


Python interface .

4. Updating records through parameterized query in


python interface .
PYTHON
PROGRAMS
.
Q1.) Read a text file line by line and
display each word separated by #.
CODING :
def wordseperated():
f=open("[Link]","r")
lines=[Link]()
for line in lines:
words=[Link]()
for word in words:
print(word+'#',end='')
print()
wordseperated()

OUTPUT :
Q2.) Read a text file and display the number
of vowels/consonants/uppercase/lowercase
characters in the file.
CODING :
def diff():
f=open("[Link]",'r')
v=c=u=l=0
data= [Link]()
for i in data:
if [Link]():
u+=1
if [Link]():
l+=1
if [Link]() in 'aeiou' :
v+=1
else:
c+=1
print("Vowels=",v)
print("Consonents=",c)
print("upper case=",u)
print("lower case=",l)
diff()

OUTPUT :
Q3.) Remove all the lines that contain the
character ‘a’ in a file and write it to
another file.
CODING :
fn1= open("[Link]",'r')
fn2= open("[Link]", 'w')
data1= [Link]()
for line in data1:
if 'a' not in line:
[Link](line)
[Link]()
[Link]()
print("task accomplished")

OUTPUT:
Q4.) Create a Binary file with name and
roll number. Search for a given roll number
and display the name, if not found display
appropriate message.
CODING :
import pickle
stu= {}
fh1=open('[Link]',"ab+")
ans= 'y'
while ans=='y' :
stu['Rollno']= int(input("Enter Rollno :"))
stu['name']= input("Enter name of student:")
[Link](stu,fh1)
ans= input("Do you want to enter more('y'/'n')...")
[Link]()

#Part 2
key=int(input("Enter the roll no to be searched:"))
fh2=open("[Link]",'rb+')
found=False
try:
while True:
stu=[Link](fh2)
if stu["Rollno"]==key:
found=True
print("The SEarched ROlno is found:")
print(stu)
except EOFError:
if found==False:
print("Searching Completed")
else:
print("The Searched Roll No does not exist:")
[Link]()

OUTPUT :
Q5.) Write a Random number generator
that generates random numbers between 1
and 6 (simulates a dice ).
CODING :
def random():
import random
s=[Link](1,6)
return s

while True:
ch=int(input("Enter 1 to Roll the dice and any other key to
exit..."))
if ch==1:
print('Dice:',random())
else:
print("Game over ")
break

OUTPUT:
Q6.) Create a binary file with roll number ,
name and marks. Input a roll number and
update the marks .
CODING :
import pickle
stu={}
fh1=open("[Link]",'ab+')
ans=input("Enter the data to file (y/n)...")
while ans=='y' or ans=='Y':
stu['Rollno']=int(input("Enter Roll Number:"))
stu['Name']=input("Enter Name:")
stu['Marks']=int(input("Enter the marks :"))
[Link](stu,fh1)
ans= input("Want to enter more?(y/n)...")
[Link]()
print()

#Part 2
key=int(input("Enter the Roll Number whose marks is to be updated :"))
fh2=open("[Link]",'rb+')
found=False
try:
while True:
pos=[Link]()
stu1=[Link](fh2)
if stu1['Rollno']==key:
stu1['Marks']=int(input("Enter the Updated Marks "))
[Link](pos)
[Link](stu1,fh2)
found=True
print("The marks are updated::")
break
except EOFError:
if found==False:
print("The Searched Rollno does not exists:")
else:
print("Program Finished ")
[Link]()
OUTPUT :
Q7.) Write a python program to implement
a stack using list.
CODING :
S=[]
c='y'
while (c=="y"):
print("[Link]")
print("[Link]")
print("[Link]")
choice=int(input("Enter your choice :"))
if (choice==1):
a=input("Enter any number :")
[Link](a)
elif (choice==2):
if(S==[]):
print("Stack Empty")
else :
print("Deleted element is :",[Link]())
elif (choice==3):
print(S)
else:
print("Wrong Input")
c=input("Do you want to continue or not?")
OUTPUT :
Q8.) Create a CSV file by entering user-id
and password, read and search the
password for given user id.
CODING :
import csv
with open("user_info.csv","w")as obj :
fileobj= [Link](obj)
while(True):
user_id = input("Enter id :")
password = input("Enter password:")
record = [user_id , password]
[Link](record)
x= input("Press Y/y to continue and N/n to end the program\n")
if x in "Nn" :
break
elif x in "Yy" :
continue
with open("user_info.csv", "r") as obj2 :
fileobj2 = [Link](obj2)
given = input("Enter the user id to be searched\n")
for i in fileobj2:
next(fileobj2)
#print(i,given)
if i[0]== given:
print(i[1])
break
OUTPUT :
Q9.) Write a method in Python to read
lines from a text file “[Link]” and
display those lines start with the alphabet
‘K’

CODING :
def display() :
file = open("[Link]",'r')
line = [Link]()
while line :
if line[0]=='K' :
print(line)
line=[Link]()
[Link]()
display()

OUTPUT :
Q10.) Write a function in python POP(Arr) ,
where Arr is a Stack implemented by a list
of number . This function returns the value
deleted from the Stack .

CODING :
def POP(Arr) :
# If stack is empty
if len(Arr)== 0 :
print("Underflow")
else :
L = len(Arr)
val = [Link](L-1)
print("DELETED ELEMENT :",val)
Arr = [12,24,36,48,60]
POP(Arr)
POP(Arr)

OUTPUT :
Q11.) A binary file “[Link]” has structure
[BookNo,Book_Name,Author,Price].
Write a user defined function CreateFile() to
input data for record and add to ‘[Link]’.

CODING :
import pickle
def createFile():
c='y'
while c=='y':
fobj = open("[Link]","ab")
BookNo= int(input("Book Number :"))
Book_name=input("Name :")
Author = input("Author :")
Price = int(input("Price :"))
rec=[BookNo,Book_n
ame,Author,Price]
[Link](rec,fobj)
print("Data added successfully")
c= input("Do you want to enter more(y/n):")
[Link]()

createFile()
OUTPUT :
Q12.) Program to input a string and count
the number of uppercase and lowercase
letters.
CODING :
# Program to count lowercase and uppercase letters in an inputted
string
str1 = input("Enter the string :")
print(str1)
upercase = 0
lwrcase = 0
i= 0
while i < len(str1):
if str1[i].islower() == True:
lwrcase += 1
if str1[i].isupper() == True :
upercase += 1
i += 1
print("No. of upercase letters in the string = ", upercase)
print("No. of lowercase letters in the string = ", lwrcase)

OUTPUT :
Q13.) Program to find maximum , minimum
, and mean value from the list .
CODING :
#Program to find maximum , minimum and mean value from the list.
list1 = []
n =int(input("Enter the number of element in the list :"))
i=0
while i < n :
x = int(input("Enter the elements of the list :"))
[Link](x)
i = i+1
print(list1)

maximum = max(list1)
minimum = min(list1)
mean = sum(list1)/len(list1)
print("Maximum value is =",maximum)
print("Minimum value is =",minimum)
print("Average value is =",mean)

OUTPUT :
Q14.) Write a Python function to sum all
the items in a list .

CODING :
def sum_list(items) :
sum_numbers = 0
for x in items :
sum_numbers += x
return sum_numbers
a = sum_list([1,2,-8])
print("The Sum of numbers of all items in a list : ", a)

OUTPUT :
Q15.) Python program to search record for
given students name from csv file .

CODING :
import csv
f = open("[Link]","r")
csv_reader = [Link](f) #csv_reader is the csv
reader object
name = input("Enter the name to be searched :")
for row in csv_reader :
if(row[0] == name ):
print(row)

OUTPUT :
COMMANDS
Q1. Consider the following table STORE
given below and write command in mysql.

Table:STORE
Storeid Name Location City NoOfEmp DateOpen SalesAmt

S101 Planet Bandra Mumbai 7 2015-10-16 4000


fashion
S102 Vogue Karol Delhi 8 2015-10-14 12000
Bagh
S103 Trends Powai Mumbai 10 2015-10-24 3000

S104 Super Thane Mumbai 11 2015-10-06 4500


Fashion
S105 Annabelle South Delhi 8 2015-10-09 4500
Ext.
S106 Rage Defence Delhi 5 2015-10-02 2000
Colony
(a ) Add records in store table.
Command:

(b) To display names of stores along with


SalesAmount of those stores that
have‘fashion’ anywhere in their store
names.
Command:
(c) To display names of the cities and the
total amount of sales on the basis of City.
Command:

(d) Add a new record with following data:


(‘S107’,’Mymart’,’Rajivchowk’,’Delhi’,9,2015-09-07,9000)

Command :
(e) Increase sales amount by 4000 whose
city is Delhi.
Command:

(f) Remove records of those whose store id


is S103.
Command:
CONNECTIVITY
(INTERFACE WITH PYTHON)
(a) To insert a new record into table
student in MYSQL using Python interface.

 CODING :

import [Link] as sqltor


dbobj=[Link](host='localhost',user='root',passwd='#
sagar2005',database='Class')
if dbobj.is_connected():
print("successfully connected")
cr=[Link]()
rno=int(input("Enter rollno of student"))
name=input("Enter name of student")
fee=int(input("Enter fee of student"))
record=(rno,name,fee) #create a tuple
query="insert into student(Rollno,Name,Fee)
values(%s,%s,%s)"
[Link](query,record)
[Link]()
print("record successfully inserted")
[Link]()

 OUTPUT :
(b) To fetch all records from student table
using Python interface .

 CODING :
import [Link] as sqltor
dbobj=[Link](host='localhost',user='root',passwd='#
sagar2005',database='Class')
if dbobj.is_connected():
print("successfully connected")
cr=[Link]()
[Link]("select * from student")
resultset=[Link]()
for i in resultset:
print(i)
[Link]()
 OUTPUT :
(c) To delete records from the table
student using Python interface .

 CODING :

import [Link] as sqltr


db =
[Link](host='localhost',user='root',passwd='#s
agar2005',database='School')
mycursor = [Link]()
query = "DELETE FROM Student where Rollno = 44 ;"
try:
[Link](query)
print([Link],"record(s) deleted")
[Link]()
except :
[Link]()
[Link]()
 OUTPUT :
(d) Updating records through
parameterized query in python interface.

 CODING :
import [Link] as sqltr
db=[Link](host='localhost',user='root',passwd='#saga
r2005',database='School')
mycursor = [Link]()
nm = 'Manish'
rn= 35
rec = (nm,rn)
query = "Update student set ExcellentStudent=%s where
Rollno=%s ;"
try:
[Link](query,rec)
print([Link],"record(s) updated")
[Link]()
except :
[Link]()
[Link]()
 OUTPUT :

You might also like