Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

PRACTICAL 1

AIM – Python program to read a text file line by line and display each
word separated by a #.

VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
st String To store contents of text file
data List To store words separated by # in the list
wrd String To store individual words of list

CONTENT OF ARTICLE.TXT
Artificial#intelligence#algorithms#are#designed#to
make#decisions,#often#using#real-
time#data.#They#are#unlike#passive#machines#that#are#capable#only
#of#mechanical#or#predetermined#responses.
CODE
myfile = open('ARTICLE.TXT','r')
st = myfile.read()
data = st.split('#')
for wrd in data:
print(wrd, end=' ')
myfile.close()

OUTPUT
Artificial intelligence algorithms are designed to make decisions, often
using real-time data. They are unlike passive machines that are capable
only of mechanical or predetermined responses.

PRACTICAL 2
AIM – Read a text file and display the number of vowels/ consonants /
uppercase / lowercase characters in the file.

VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
st String To store contents of text file
ch String To store individual characters from the
string
vow int To store count of vowels
con int To store count of consonants
upp int To store count of uppercase characters
low int To store count of lower case characters
oth int To store count of other characters

~1~
CONTENT OF PYTHON.TXT
What is Python? #EXECUTIVE SUMMARY@2020!#
Python is an interpreted, object-oriented, high-level programming
language with dynamic semantics. It is more efficient than other 3rd
and 4th GENERATION LANGUAGES.

CODE
myfile = open('PYTHON.TXT','r')
vow = con = upp = low = oth = 0
st = myfile.read()
for ch in st:
if ch.isalpha():
if ch.isupper():
upp += 1
if ch.islower():
low += 1
if ch.upper() in 'AEIOU':
vow += 1
else:
con += 1
else:
oth += 1
print('Total Uppercase characters =',upp)
print('Total Lowercase characters =',low)
print('Total vowels =',vow)
print('Total consonants =',con)
print('Other characters =',oth)
myfile.close()

OUTPUT
Total Uppercase characters = 39
Total Lowercase characters = 124
Total vowels = 60
Total consonants = 103
Other characters = 43

PRACTICAL 3
AIM – Python program to copy all the lines that contain the character
'a' from a file and write them to another file.

VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
data List To store contents of text file as list of
strings(lines)
line String To store individual lines from the list data

~2~
CONTENTS OF FARMER.TXT
A farmer looking for a source of water for his farm.
He bought one well from his neighbour.
The neighbour was cunning.
I sold the well to you.
The farmer didn’t know what to do.
So he went to Birbal.

CODE
myfile = open('FARMER.TXT','r')
tofile = open('OUTFILE.TXT', 'w')
data = myfile.readlines()
for line in data:
if 'a' in line:
tofile.write(line)
myfile.close()
tofile.close()

OUTPUT
CONTENTS OF OUTFILE.TXT
A farmer looking for a source of water for his farm.
The neighbour was cunning.
The farmer didn’t know what to do.
So he went to Birbal.

PRACTICAL 4
AIM – Python program to read a file and display all the lines in reverse
order.

VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
data List To store contents of text file as list of
strings(lines)
line String To store individual lines from the list data
c String To store individual character of line

CONTENTS OF STORY.TXT
Ten pundits (holy men) went to the Ganga to take a dip in the river.
They held each other’s hands as they took dips thrice.
When they came up the third time, they were not holding hands.
“Let’s make sure all of us have come out of the river safely.”
I will count.

~3~
CODE
myfile = open('STORY.TXT','r')
data = myfile.readlines()
for line in data:
for c in range(len(line)-2,-1,-1):
print(line[c], end='')
print()
myfile.close()

OUTPUT
.revir eht ni pid a ekat ot agnaG eht ot tnew )nem yloh( stidnup neT
.ecirht spid koot yeht sa sdnah s'rehto hcae dleh yehT
.sdnah gnidloh ton erew yeht ,emit driht eht pu emac yeht nehW
".ylefas revir eht fo tuo emoc evah su fo lla erus ekam s'teL"
.tnuoc lliw I

PRACTICAL 5
AIM – Python program to read a text file and display all the words
which starts with c or C.

VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
st String To store contents of text file as string
data List To store individual words from the string
wrd String To store individual words(elements) from
data

CONTENTS OF STORY2.TXT
Ten pundits (holy men) went to the Ganga to take a dip in the river.
They held each other’s hands as they took dips thrice.
When they came up the third time, they were not holding hands.
“Let’s make sure all of us have come out of the river safely.”
I will COUNT.

CODE
myfile = open('STORY2.TXT','r')
st = myfile.read()
data = st.split()
for wrd in data:
if wrd[0] == 'c' or wrd[0] == 'C':
print(wrd, end=' ')
myfile.close()

OUTPUT
came come COUNT.

~4~
PRACTICAL 6
AIM – Python program to read a text file, creates a new file where each
character's case is inverted.

VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
data String To store the contents of text file in a string
c String To store individual characters(elements)
from data

CONTENTS OF STORY3.TXT
Ten PUNDITS (holy men) went to the GANGA to take a dip in the river.
THEY HELD EACH OTHER'S HANDS AS THEY TOOK DIPS THRICE.
When they came up the third time, they were not HOLDING Hands.
"Let's make SURE ALL of us have come out of the RIVER Safely."
I will COUNT.

CODE
file = open('STORY3.TXT','r')
outfile = open('NEWFILE.TXT','w')
data = file.read()
for c in data:
if c.isupper():
outfile.write(c.lower())
else:
outfile.write(c.upper())
file.close()
outfile.close()

print('CONTENTS OF NEW FILE')


file = open('NEWFILE.TXT','r')
data = file.read()
for c in data:
print(c,end='')

OUTPUT
CONTENTS OF NEW FILE
tEN pundits (HOLY MEN) WENT TO THE ganga TO TAKE A DIP IN THE
RIVER.
they held each other's hands as they took dips thrice.
wHEN THEY CAME UP THE THIRD TIME, THEY WERE NOT holding
hANDS.
"lET'S MAKE sure all OF US HAVE COME OUT OF THE river sAFELY."
i WILL count.

~5~
PRACTICAL 7
AIM – Program to read a text file and display the total number of lines
words and characters.
Also Count and Display all words which starts with t or T

VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
filename String To accept the file name to be opened from
the user.
data List To store individual words from the string
lines Int To store count of lines
words Int To store count of words
chars Int To store count of characters
wrd String To store individual words
count Int To store count of words that starts with t or
T

CONTENTS OF STORY3.TXT
Ten PUNDITS (holy men) went to the GANGA to take a dip in the river.
THEY HELD EACH OTHER'S HANDS AS THEY TOOK DIPS THRICE.
When they came up the third time, they were not HOLDING Hands.
"Let's make SURE ALL of us have come out of the RIVER Safely."
I will COUNT.

CODE
filename =input('Enter the file to open : ')
myfile = open(filename,'r')
data = myfile.read()
lines = len(data.split('\n'))
words = len(data.split(' '))
chars = len(data)
print('Total lines =',lines)
print('Total words =', words)
print('Total characters =',chars)
print('\nList of words that starts with t or T')
count = 0
for wrd in data.split(' '):
if wrd[0] == 't' or wrd[0] == 'T':
count += 1
print(wrd, end=' ')
print("\nTotal words that starts with 't' or 'T' = ", count)

OUTPUT
Enter the file to open : STORY3.TXT
Total lines = 6
Total words = 51
Total characters = 266

~6~
List of words that starts with t or T
Ten to the to take the THEY TOOK THRICE. they the third time, they
the
Total words that starts with 't' or 'T' = 15

PRACTICAL 8
AIM – Develop a Python program that accepts Roll Number, Name and
Percentage of multiple students and save the information into a binary
file. After accepting all records display the contents of binary file on
the screen

VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
fil File object File object associated to binary file
stufile.dat for writing purpose.
stu Dictionary To store roll number, name and percentage
of a student.
rno int Dictionary element to store roll number
name String Dictionary element to store name of student
percent float Dictionary element to store percentage of
student
rn int Variable to store roll number
nm String Variable to store name of student
pr float Variable to store percentage of student

CODE
import pickle
fil = open('stufile.dat', 'wb')
choice = 'Y'
stu = { }
while choice.upper() == 'Y':
rn = int(input('Enter roll number : '))
nm = input('Enter student name : ')
pr = float(input('Enter percentage : '))

#add above data into dictionary


stu['rno'] = rn
stu['name'] = nm
stu['percent'] = pr

#write dictionary into binary file


pickle.dump(stu, fil)

~7~
choice = input('Want to enter more data y/n : ')
print('Data written into binary file!!!!')
fil.close()

#Display Contents of stufile.dat


fil = open('stufile.dat','rb')
dt={ }
print('Contents of stufile.dat')
try:
while True:
dt = pickle.load(fil)
print(dt)
except:
fil.close()

OUTPUT
Enter roll number : 101
Enter student name : Anand
Enter percentage : 78.5
Want to enter more data y/n : y
Enter roll number : 102
Enter student name : Manish Mishra
Enter percentage : 88.1
Want to enter more data y/n : n
Data written into binary file!!!!

Contents of stufile.dat
{'rno': 101, 'name': 'Anand', 'percent': 78.5}
{'rno': 102, 'name': 'Manish Mishra', 'percent': 88.1}

PRACTICAL 9
AIM - Develop a python program to accept Employee Number,
Employee Name, Salary and Department into a List, and save the
details of employees into binary file named COMPANY.DAT. After
creating the binary file accept employee number from the user and
search it in the binary file and display the information of the employee.

VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
fil File object File object associated to binary file
COMPANY.DAT for both reading and writing
purpose.
emp List To store employee number, name, salary
and department

~8~
rn Int Variable to store employee number
nm String Variable to store name of employee
sal Float Variable to store salary of employee
dep String Variable to store department of employee

CODE
import pickle
fil = open('COMPANY.DAT', 'wb+') #Binary file opened for both reading and writing
choice = 'Y'
emp = [ ]
while choice.upper() == 'Y':
en = int(input('Enter employee number : '))
nm = input('Enter employee name : ')
sal = float(input('Enter employee salary : '))
dep = input("Enter employee's department : ")

#add above data into list


emp = [en, nm, sal, dep]

#write list into binary file


pickle.dump(emp, fil)

choice = input('Want to enter more data y/n : ')


print('Data written into binary file!!!!')

#Code to search employee based on employee number


fil.seek(0)
emp = [ ]
en = int(input('Enter employee number whose record is to be searched :
'))
found = False

try:
print('Details of employee')
while True:
emp = pickle.load(fil)
if emp[0] == en:
print(emp)
found = True
except:
if not found:
print('Record NOT found')
fil.close()

~9~
OUTPUT
Enter employee number : 101
Enter employee name : Rima Sen
Enter employee salary : 50000
Enter employee's department : Administration
Want to enter more data y/n : y
Enter employee number : 104
Enter employee name : Jagdish Mishra
Enter employee salary : 30000
Enter employee's department : Sales
Want to enter more data y/n : y
Enter employee number : 108
Enter employee name : Om Lakhan
Enter employee salary : 40000
Enter employee's department : Sales
Want to enter more data y/n : n
Data written into binary file!!!!

Enter employee number whose record is to be searched : 108


Details of employee
[108, 'Om Lakhan', 40000.0, 'Sales']

PRACTICAL 10
AIM – A binary file “Books.dat” has structure [BookNo, Book_Name,
Author, Price].
i. Write a user defined function CreateFile() to input data for a
record and add to Books.dat .
ii. Write a function CountRec(Author) in Python which accepts the
Author name as parameter and count and return number of
books by the given Author are stored in the binary file
“Books.dat”
Develop Python code to create and test the above user defined
functions.

VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
fil File object File object associated to binary file
BOOKS.DAT
bn Int Variable to store book number
nm String Variable to store name of book
price Float Variable to store price of book
au String Variable to store author of book
choice String To accept user’s choice
book List To store details of one book

~ 10 ~
Author String Function parameter to receive author’s
name

CODE
def CreateFile():
import pickle
fil = open('BOOKS.DAT', 'wb') #Binary file opened for writing
choice = 'Y'
while choice.upper() == 'Y':
bn = int(input('Enter book number : '))
nm = input('Enter book name : ').upper()
au = input('Enter author name : ').upper()
price = float(input('Enter price of the book : '))

#add above data into list


book = [bn, nm, au, price]

#write list into binary file


pickle.dump(book, fil)

choice = input('Want to enter more data y/n : ')


print('Data written into binary file!!!!')
fil.close()

def CountRec(Author):
import pickle
fil = open('BOOKS.DAT', 'rb') #Binary file opened for reading
book = [ ]
tot = 0
try:
while True:
book = pickle.load(fil)
if book[2] == Author:
tot = tot + 1
except:
fil.close()
return tot

CreateFile()
Author = input('Enter auther name to search and count : ').upper()
print('Total books of author',Author, 'is/are',CountRec(Author))

OUTPUT
Enter book number : 111
Enter book name : C++ Programming
Enter author name : E Balaguruswamy
Enter price of the book : 400

~ 11 ~
Want to enter more data y/n : y
Enter book number : 112
Enter book name : C Programming
Enter author name : E Balaguruswamy
Enter price of the book : 350
Want to enter more data y/n : y
Enter book number : 115
Enter book name : Learn Python
Enter author name : S John
Enter price of the book : 500
Want to enter more data y/n : y
Enter book number : 118
Enter book name : Computer Basics
Enter author name : P K Sinha
Enter price of the book : 288
Want to enter more data y/n : n
Data written into binary file!!!!

Enter author name to search and count : E Balaguruswamy


Total books of author E BALAGURUSWAMY is/are 2

PRACTICAL 11
AIM – Develop a Python program to create a binary file “STUDENT.DAT”
has structure (admission_number, Name, Percentage). Write a function
countrec() in Python that would read contents of the file
“STUDENT.DAT” and display the details of those students whose
percentage is above 75. Also display number of total students and
number of students scoring above 75%.

VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
fil File object File object associated to binary file
STUDENT.DAT
admno Int Variable to store admission number
nm String Variable to store name of student
percent Float Variable to store percentage of student
choice string To accept user’s choice
stu Tuple To store details of one student
tot Int To store total number of students
dis Int To store number of students having more
than 75%

CODE

~ 12 ~
def CreateFile():
import pickle
fil = open('STUDENT.DAT', 'wb') #Binary file opened for writing
choice = 'Y'
while choice.upper() == 'Y':
admno = int(input('Enter admission number : '))
nm = input('Enter name : ')
percent = float(input('Enter percentage : '))

#add above data into list


stu = (admno, nm, percent)

#write list into binary file


pickle.dump(stu, fil)

choice = input('Want to enter more data y/n : ')


print('Data written into binary file!!!!')
fil.close()

def CountRec():
import pickle
fil = open('STUDENT.DAT', 'rb') #Binary file opened for reading
stu = ()
tot = dis = 0
try:
print('Details of students having percentage more than 75 ')
while True:
stu = pickle.load(fil)
tot = tot + 1
if stu[2] > 75.0:
print(stu)
dis = dis + 1
except:
fil.close()
print('Total students = ', tot)
print('Number of students securing more than 75% = ', dis)

CreateFile()
CountRec()

OUTPUT
Enter admission number : 111
Enter name : Rahul K
Enter percentage : 65.8
Want to enter more data y/n : y
Enter admission number : 112
Enter name : Jaya Kumari
Enter percentage : 78
Want to enter more data y/n : y

~ 13 ~
Enter admission number : 115
Enter name : Taposh Kumar
Enter percentage : 55.5
Want to enter more data y/n : y
Enter admission number : 118
Enter name : Ram Singh
Enter percentage : 98.8
Want to enter more data y/n : n
Data written into binary file!!!!

Details of students having percentage more than 75


(112, 'Jaya Kumari', 78.0)
(118, 'Ram Singh', 98.8)

Total students = 4
Number of students securing more than 75% = 2

PRACTICAL 12
AIM – A binary file stufile.dat contains records of students in the
structure {'rno':roll Number,'name':Name of student,
'percent':Percentage of student}. Develop a python program to
change/update the details of a particular student based on Roll Number
in the binary file.

VARIABLE DESCRIPTION
Variable/Object Data Type Description
Name
fil File object File object associated to binary file
stufile.dat. Opened for reading and writing.
rn Int Variable to store roll number
rno Int Dictionary key to store roll number
name String Dictionary key to store name of student
percent Float Dictionary key to store percentage of student
pos int To store position of file pointer
stu Dictionary To store details of one student
nm String To store new name of student
pr Float To store new percentage of student
found Boolean To store status of record, whether found or
not.

CODE
import pickle
stu = { }
fil = open('stufile.dat','rb+') #File opened for reading and writing both

~ 14 ~
rn = int(input('Enter roll no of student whose record you want to update
: '))
found = False

#Search the dictionary having above roll number in the binary file
try:
while True:
pos = fil.tell()
stu = pickle.load(fil)
if stu['rno'] == rn:
print('Name of student : ',stu['name'])
nm = input('Enter modified name of student : ')
stu['name'] = nm
print('Percentage of student : ',stu['percent'])
pr = float(input('Enter modified percent : '))
stu['percent'] = pr

#Go back to the start position of current record in binary file


fil.seek(pos)

#Overwrite the modifed record


pickle.dump(stu, fil)

found = True
except:
if found:
print('Record updated !!!')
else:
print('Sorry!!!Record not found')
fil.close()

OUTPUT
Enter roll no of student whose record you want to update : 102
Name of student : Manish Mishra
Enter modified name of student : Manisha Mehta
Percentage of student : 88.1
Enter modified percent : 98.8
Record updated !!!

PRACTICAL 13
AIM – Develop a Python program to create csv file named EMP.csv to
store employee no, name and salary of more than one employees.

VARIABLE DESCRIPTION

~ 15 ~
Variable/Object Data Type Description
Name
fh File object File object associated to csv file EMP.csv
Opened for writing.
Eno Int Variable to store employee number
En String Variable to store name of employee
Sl Int Variable to store employee salary
Choice String To store choice
Erec List To store details of one employee

CODE
import csv
fh = open('EMP.csv','w', newline='')

ewriter = csv.writer(fh) #Default delimiter i.e. comma


ewriter.writerow(['EmpNo', 'Ename', 'Salary'])

choice = 'Y'
while choice.upper()=='Y':
eno = int(input('Enter employee number : '))
en = input('Enter employee name : ')
sl = int(input('Enter salary : '))
erec = [eno, en, sl]
ewriter.writerow(erec) #or ewriter.writerow([eno,en, sl])
choice = input('Want to enter more records y/n : ')
fh.close()

OUTPUT
Contents of EMP.csv file

EmpNo Ename Salary


1001 Raj Malhotra 88000
1004 Diksha Sharma 85000
1005 Umesh Ratan 65000
1008 Ram Singh 89000

PRACTICAL 14
AIM – Write a python program to implement a function showPrime(n)
that accepts n as parameter and display prime numbers upto n, using
another function isPrime(i) that checks whether i is prime or not.

VARIABLE DESCRIPTION

~ 16 ~
Variable/Object Data Type Description
Name
N Int To read value of n (Number)
p Bool To check whether number is prime
d Int To store an integer

CODE
def isPrime(n):
p=True
d=2
while d<=pow(n,0.5) and p:
if n%d==0:
p=False
else: d+=1
return p
def showPrime(n):
print("Prime numbers in the range 1 to",n,"are: ")
for i in range(2,n+1):
if isPrime(i): #Calling isPrime() from showPrime()
print(i,end=" ")

print("To display prime numbers from 1 to n:")


n=int(input("Enter the value of n: "))
showPrime(n)

OUTPUT
To display prime numbers from 1 to n:
Enter the value of n: 25
Prime numbers in the range 1 to 25 are:
2 3 5 7 11 13 17 19 23

PRACTICAL 15 – SQL QUERIES

PRACTICAL 16
AIM: Python program to implement a stack where each node is a list
that contains Roll Number, Name and Percentage of a student

VAIRABLE DESCRIPTION

Variable/Object Data Type Scope Description


Name
stack list Global To store nodes in the form
of list
rno int Local to PUSH_STU() To store roll number of
student
nm string Local to PUSH_STU() To store name of student

~ 17 ~
pr float Local to PUSH_STU() To store percent of student

stu list Local to PUSH_STU() To store roll no. name and


percent
top int Local to DISPLAY() To store the index of
topmost node
n int DISPLAY() To control loop

CODE:
def PUSH_STU():
rno = int(input('Enter Roll number : '))
nm = input('Enter name : ')
pr = float(input('Enter percentage : '))
stu = [rno,nm,pr]
stack.append(stu)
def POP_STU():
if stack == []:
print('Stack is empty')
else:
print('Node deleted = ', stack.pop())
def PEEK_STU():
if stack == []:
print('Stack is empty')
else:
print('Top node = ', stack[len(stack)-1])
def DISPLAY():
if stack == []:
print('Stack is empty')
else:
print('STACK NODES')
top = len(stack)-1
print(stack[top], "<--Top")
for n in range(top-1, -1, -1):
print(stack[n])
#main
stack=[] #Initialisation of stack
while True:
print('\nSTACK OPERATIONS')
print('1. Push')
print('2. Pop')
print('3. Peek')
print('4. Display stack')
print('5. Exit')
ch = int(input('Enter your choice(1-5) : '))
if ch == 1:
PUSH_STU()
elif ch == 2:
POP_STU()
elif ch == 3:
PEEK_STU()
elif ch == 4:
~ 18 ~
DISPLAY()
elif ch == 5:
break
else:
print('Invalid choice')

OUTPUT:
STACK OPERATIONS
1. Push
2. Pop
3. Peek
4. Display stack
5. Exit
Enter your choice(1-5) : 1
Enter Roll number : 101
Enter name : Rahul
Enter percentage : 89

STACK OPERATIONS
1. Push
2. Pop
3. Peek
4. Display stack
5. Exit
Enter your choice(1-5) : 1
Enter Roll number : 102
Enter name : Nisha
Enter percentage : 75.8

STACK OPERATIONS
1. Push
2. Pop
3. Peek
4. Display stack
5. Exit
Enter your choice(1-5) : 4
STACK NODES
[102, 'Nisha', 75.8] <--Top
[101, 'Rahul', 89.0]

STACK OPERATIONS
1. Push
2. Pop
3. Peek
4. Display stack
5. Exit
Enter your choice(1-5) : 3
Top node = [102, 'Nisha', 75.8]

STACK OPERATIONS
1. Push
2. Pop

~ 19 ~
3. Peek
4. Display stack
5. Exit
Enter your choice(1-5) : 2
Node deleted = [102, 'Nisha', 75.8]

STACK OPERATIONS
1. Push
2. Pop
3. Peek
4. Display stack
5. Exit
Enter your choice(1-5) : 4
STACK NODES
[101, 'Rahul', 89.0] <--Top

STACK OPERATIONS
1. Push
2. Pop
3. Peek
4. Display stack
5. Exit
Enter your choice(1-5) : 5

PRACTICAL 17
AIM: Create a dictionary containing product names and price as key
value pairs of 4 products. Write a program, with separate user defined
functions to perform the following operations:
•Push the price of the dictionary into a stack, where the corresponding
product name starts with character S.
•Pop and display the contents of the stack one by one.

VARIABLE DESCRIPTION

Variable/Object Data Type Scope Description


Name
PROD Dictionary Global To store names and price
of products as key:value
pairs.
stack List Global To store product price on
each node
k String Local to To store key i.e. name of
PUSH_PROD() the product.
v Int Local to To store value i.e. price of
PUSH_PROD() the product.

CODE:
PROD = {'SAMOSA':25 , 'Pizza':550 , 'Sandwich': 150 , 'Noodles':200}
stack = []

~ 20 ~
def PUSH_PROD():
for k,v in PROD.items():
if k[0] in 'Ss':
stack.append(v)
def POP_PROD():
if stack == []:
print('Stack is empty')
else:
while stack != []:
print(stack.pop())

PUSH_PROD()
print('STACK NODES')
POP_PROD()

OUTPUT:
STACK NODES
150
25

PRACTICAL 18
AIM: Python program to create student table in mysql and insert data
using python interface.

VARIABLE DESCRIPTION

Variable/Object Data Type Description


Name
con mysql.connector Object to create connection with
MySQL
mcur Cursor object To create cursor object.

rn Int To store roll no of student

nm String To store name of student

dt String To store date of birth of student

pr Float To store percentage of student

qry String To store SQL query

val Tuple To store value to be merged with SQL


query.
choice String To store/read choice from the user.

CODE:

~ 21 ~
import mysql.connector as ms
con = ms.connect(host='localhost', user='root', passwd='tiger',
database='employee')
if con.is_connected():
print('Connected')
mcur = con.cursor()
mcur.execute('CREATE TABLE IF NOT EXISTS STUDENT (RNO INT(3)
PRIMARY KEY, SNAME VARCHAR(20),
DOB DATE, PERCENT FLOAT(6,2));')

#INSERTING DATA
choice = 'y'
while choice in 'Yy':
rn = int(input('Enter roll number : '))
nm = input('Enter students name : ')
dt = input('Enter date of birth YYYY-MM-DD : ')
pr = float(input('Enter percentage : '))
qry = 'INSERT INTO STUDENT VALUES(%s, %s, %s, %s);'
val = (rn, nm, dt, pr)
mcur.execute(qry, val)
choice = input('Enter more records y or Y for yes : ')
con.commit()
con.close()
print('Records inserted OK !')

OUTPUT:
Connected
Enter roll number : 101
Enter students name : Raj
Enter date of birth YYYY-MM-DD : 2000-08-20
Enter percentage : 89.8
Enter more records y or Y for yes : y
Enter roll number : 102
Enter students name : Sita Ram
Enter date of birth YYYY-MM-DD : 2000-02-02
Enter percentage : 98.8
Enter more records y or Y for yes : n
Records inserted OK !

PRACTICAL 19
AIM: Python program to display all records of STUDENT table.

VARIABLE DESCRIPTION

Variable/Object Data Type Description


Name
con mysql.connector Object to create connection with
MySQL
mcur Cursor object To create cursor object.

~ 22 ~
rows List of tuples To store records fetched from
STUDENT table.
r Tuple To store one row as tuple.

CODE:
import mysql.connector as ms
con = ms.connect(host='localhost', user='root', passwd='tiger',
database='employee')
if con.is_connected():
print('Connected')
mcur = con.cursor()
mcur.execute('SELECT * FROM STUDENT;')
rows = mcur.fetchall()
for r in rows:
print(r)
#date = r[2]
#print(date.day,'-',date.month,'-',date.year)
con.close()

OUTPUT:
Connected
(101, 'Raj', datetime.date(2000, 8, 20), 89.8)
(102, 'Sita Ram', datetime.date(2000, 2, 2), 98.8)

PRACTICAL: 20
AIM: Python program to accept percentage and display records of those
students whose percentage is more than the value of percentage.

VARIABLE DESCRIPTION

Variable/Object Data Type Description


Name
con mysql.connector Object to create connection with
MySQL
mcur Cursor object To create cursor object.

per Float To store percentage of student

qry String To store SQL query

rows List of tuples To store records fetched from


STUDENT table.
r Tuple To store one row as tuple.

CODE:
import mysql.connector as ms
con = ms.connect(host='localhost', user='root', passwd='tiger',
database='employee')
~ 23 ~
if con.is_connected():
print('Connected')
mcur = con.cursor()
per = float(input('Enter percentage : '))
qry = 'SELECT * FROM STUDENT WHERE PERCENT >= {};'.format(per)
mcur.execute(qry)
rows = mcur.fetchall()
for r in rows:
print(r)
con.close()

OUTPUT:
Connected
Enter percentage : 90
(102, 'Sita Ram', datetime.date(2000, 2, 2), 98.8)

PRACTICAL 21
AIM: Python program to read Roll Number of a student and update the
record in MySQL with new values.

VARIABLE DESCRIPTION

Variable/Object Data Type Description


Name
con mysql.connector Object to create connection with
MySQL
mcur Cursor object To create cursor object.

rn Int To store roll no of student

nm String To store name of student

dt String To store date of birth of student

pr Float To store percentage of student

qry String To store SQL query

val Tuple To store value to be merged with SQL


query.
choice String To store/read choice from the user.

CODE:
import mysql.connector as ms
con = ms.connect(host='localhost', user='root', passwd='tiger',
database='employee')
if con.is_connected():
print('Connected')
mcur = con.cursor()
rn = int(input('Enter roll number to update : '))
~ 24 ~
mcur.execute('SELECT * FROM STUDENT WHERE RNO=%s',(rn,))
rows = mcur.fetchall()
if rows:
print('Existing values for Roll Number : ', rn)
for r in rows:
print(r)
nm = input('Enter new name : ')
dt = input('Enter new date YYYY-MM-DD : ')
pr = float(input('Enter new percentage : '))
qry = 'UPDATE STUDENT SET SNAME=%s, DOB=%s, PERCENT=%s
WHERE RNO=%s'
val = (rn, dt, pr, rn)
mcur.execute(qry, val)
print('Record Updated OK!')
con.commit()
else:
print('Sorry not found !')
con.close()

OUTPUT:
Connected
Enter roll number to update : 101
Existing values for Roll Number : 101
(101, 'Raj', datetime.date(2000, 8, 20), 89.8)
Enter new name : Raju Singh
Enter new date YYYY-MM-DD : 2001-12-25
Enter new percentage : 88.8
Record Updated OK!

PRACTICAL 22
AIM: Python program to read Roll Number of a student and delete that
record from STUDENT table in MySQL.

VARIABLE DESCRIPTION

Variable/Object Data Type Description


Name
con mysql.connector Object to create connection with
MySQL
mcur Cursor object To create cursor object.

rn Int To store roll no of student

qry String To store SQL query

rows List of tuples To store records fetched from


STUDENT table.
r Tuple To store one row as tuple.

~ 25 ~
CODE:
import mysql.connector as ms
con = ms.connect(host='localhost', user='root', passwd='tiger',
database='employee')
if con.is_connected():
print('Connected')
mcur = con.cursor()
rn = int(input('Enter roll number to delete : '))
mcur.execute('SELECT * FROM STUDENT WHERE RNO=%s',(rn,))
rows = mcur.fetchall()
if rows:
print('Existing values for Roll Number : ', rn)
qry = 'DELETE FROM STUDENT WHERE RNO=%s'
mcur.execute(qry, (rn,))
print('Record Deleted OK!')
con.commit()
else:
print('Sorry not found !')
con.close()

OUTPUT:
Connected
Enter roll number to delete : 101
Existing values for Roll Number : 101
Record Deleted OK!

~ 26 ~

You might also like