You are on page 1of 30

FIBONACCI SERIES

Ex. No. 1
Question :
Write a python program to print Fibonacci series using
function
Aim :
To print Fibonacci series using function

Source code:
def fibonacci(n):
first_term=-1
second_term=1
for i in range(n):
third_term=first_term+second_term
print(third_term,end=' ')
first_term=second_term
second_term=third_term
print("Fibonacci series")
n=int(input("Enter the number of terms you want to
print"))
fibonacci(n)

Result:
The above program has been executed successfully
PALINDROME

Ex. No. 2
Question
Write a program to check whether the string is
palindrome or not.
Aim:
To check whether the string is palindrome or not.
Source code
def palindrome(mylength):
for i in(0,mylength//2):
if mystring[i]!=mystring[mylength-i-1]:
print("The given string",mystring,"is not a
palindrome")
break
else:
continue
else:
print("The given string",mystring,"is a
palindrome") print("Check Palindrome")
mystring=input("Enter a string: ")
mylength=len(mystring)
palindrome(mylength)

Result:
The above program has been executed
successfully
PRINTING THE LARGEST AND SMALLEST COUNTRY NAME IN A LIST

Ex. No. 3

Question

Write a python program to print the largest and smallest country name
in a given list

Aim:
To create a list with different country names and print the smallest
country
Source code
def maxmin(n):
country=[ ]
for i in range(n):
cname=input("Enter the country name : ")
country.append(cname)
country.sort(key=len)
print('Country with the smallest length = ',country[0])
print('Country with the largest length= ',country[len(country)-1])
n=int(input('Enter the no. of country: '))
maxmin(n)

Result:
The above program has been executed successfully
MENU DRIVEN PROGRAM TO CALCULATE AREA OF DIFFERENT SHAPES

Ex. No. 4

Question :
Write a python program to calculate area of different shapes using menu
driven programs
Aim:
To develop a menu driven program to calculate the area of different shapes
using functions Source code:
def area(choice):
if choice==1:
side=int(input("Enter your side value:"))
areasq=side* side
print('Area of a square=',areasq)
elif choice==2:
length=int(input('Enter the length value :'))
breadth=int(input("Enter the Breadth value:"))
arearec=length*breadth
print('Area of a rectangle =',arearec)
elif choice==3:
base=int(input("Enter the base value:"))
height=int(input("Enter the height value :"))
areatri=0.5*base* height
print('Area of a triangle =',areatri)
elif choice==4:
exit
print('Menu Driven program to compute the Area of different shapes')
print('----------------------------------------------------------------------------------------------')
print('1. To compute area of a square')
print('2. To compute area of rectangle')
print('3. To compute area of a triangle')
print('4.Exit')
choice=int(input("Enter your choice between 1 to 4: "))
if choice<1 or choice>4:
print('wrong choice')
else:
area(choice)
Result:
The above program has been executed successfully
SEARCH AND DISPLAY USING DICTIONARY
Ex. No. 5
Question
Write a python program to store roll number and name of 5
students and search student name through roll no.

Aim
To create a dictionary to store roll number and name of 5 students, for a
given roll number display the corresponding name else display error
message
Source code:
mydict={ }
def inputdictionary():
for i in range(5):
rno=int(input("Enter the roll no :"))
name=input("Enter the name :")
mydict[rno]=name
print(mydict)
def search(n):
found=0
for i in mydict:
if i==n:
found=1
print('The element is found')
print(i,' ', mydict[i])
break;
if found==0:
print(n,'is not found in the dictionary')
inputdictionary()
n=int(input("Enter the Roll number to be searched : " ))
search(n)

Result:
The above program has been executed successfully
RANDOM NUMBER GENERATION

Ex.No. 6

Question
Write a python program to generate random numbers between 1 to 6
(simulates a dice)
Aim
To generate random numbers between 1 to 6
Source code
import random
Guess=True
while Guess:
n=random.randint(1,6)
userinput=int(input("Enter a number between 1 t0 6:"))
if userinput==n:
print("Congratulations !!!. you won the lottery")
else:
print("Sorry ,Try again. The lucky number was ",n)
val = input("Do you want to continue y/n")
if val in ['Y','y']:
Guess=True
else:
Guess=False

Result:
The above result has been executed successfully.
READ A TEXT FILE LINE AND PRINT # AFTER EACH WORD

Ex.No.7
Question
Write a python program to read a text file line by line and display each word
separated by ‘#’.
Aim:
To read a text file line by line and display each word separated by ‘#’.
Source code:

def add():
with open('Mystory.txt') as f:
lines=f.readlines()
Mylist=[]
for i in lines:
Mylist=i.split()
for j in Mylist:
print(j,"#",end =" ")
add()

Result:
The above result has been executed successfully.
PRINTING ALL THE LINES STARING WITH ‘T’
Ex.No.8
Question
Write a python program to read a text file and print all the lines that are
starting with ‘T’ on the screen.

Aim
To read a text file and print all the lines that are starting with
‘T’ on the screen.

Source code
def print_lines():
with open("Mystory.txt") as f:
Reader=f.readlines()
for line in Reader:
if line[0]=='T':
print(line)
print_lines()

Result:
The above result has been executed successfully.
COUNING THE NUMBER OF OCCURENCES OF ‘IS’ AND ‘AND ‘ IN A TEXT FILE

Ex.No. 9

Question
Write a python program to read a text file and count the number of
occurrences of ‘is’ and ‘and’ in that file
Aim
To read a text file and count the number of occurrences of ‘is’ and ‘and’
in that file
Source code

def count_word():
with open('Mystory.txt','r') as rfile:
reader=rfile.readlines()
print(reader)
count=0
for line in reader:
words=line.split()
for i in words:
if i=='is' or i=='and':
count+=1
print('The total no. of words with is / and =',count) count_word()

Result:
The above result has been executed successfully.
COUNTING VOWELS, CONSANANTS, DIGITS, SPECIAL, CHARACTERS, LOWER CASE &
UPPDER CASE LETTERS IN A TEXT FILE
Ex.No. 10
Question
Write a python program to count the number of vowels, consonants digits, special
characters , lower case and upper case letters in a text files
Aim
To count the number of vowels, consonants digits, special characters ,
lower case and upper case letters in a text files
Source code
import string
def text_count():
ucase=lcase=vowels=consonants=digits=special=0
with open('Mystory.txt') as rtfile:
read =rtfile.read()
for ch in read:
if ch.isalpha():
if ch in ['a','e','i','o','u','A','E','I','O','U']:
vowels+=1
else:
consonants +=1
if ch.isupper():
ucase+=1
if ch.islower():
lcase+=1
elif ch.isdigit():
digits +=1
else:
special+=1
print('No. of uppercase alphabets =',ucase)
print('No. of lowercase alphabets =',lcase)
print('No. of digits =',digits)
print('No. of vowels =',vowels)
print('No. of consonants =',consonants)
print('No. of special characters =',special)
text_count()
Result:
The above result has been executed successfully.
WRITE A PROGRAM THAT READS A TEXT FILE AND CREATE A NEW FILE AFTER
ADDING "ING" TO ALL WORDS ENDING WITH "T", "P", "D".
EX.No. 11

Question
write a python program that reads a text file and create a new file after adding "ing"
to all words ending with "t", "p", "d".
Aim
To reads a text file and create a new file after adding "ing" to all words ending with
"t", "p",
"d".
Source code:
x=open("f1.txt","r")
y=open("f2.txt","w")
x1=x.readlines()
for i in x1:
l=""
for j in i :
if j[-1]=="t" or j[-1]=="p" or j[-
1]=="d": l+=i +"ing"
else:
l+=i
y.write(l)
x.close()
y.close()
with open("f2.txt","r") as wf:
print(wf.read())

Result:
The above program has been executed successfully
STORING AND RETRIEVING STUDENT’S INFORMATION USING
CSV FILE

Ex.No.12

Question
Write a python program to storing and retrieving student’s
information using csv file

Aim
To storing and retrieving student’s information using
csv file

Source code:

import csv
Stu=[]
def write_csv_data():
with
open('Inputdata.csv','a',newline='')as F:
write=csv.writer(F)
ch='y'
while ch =='y':
name=input ('Enter the student name:')
totalmarks=int(input('total marks:'))
stu=[name,totalmarks]
write.writerow(stu)
ch=input('do u want to continue y/n :')

def read_csv_data():
with open('Inputdata.csv','r')as F:
reader=csv.reader(F)
print("Stu_Name \t Total Mark \t Average")
for data in reader:
print(data[0],'\t\t',int(data[1]),'\t\t',int(data[1])/5)
write_csv_data()
read_csv_data()

Result:
The above program has been executed successfully
COPYNING THE CONTENTS OF ONE CSV FILE TO ANOTHER USING
DIFFERENT DELIMITER
EX. NO 13
Question
Write a python program to copying the contents of one csv
file to another using different delimiter

Aim
To copying the contents of one csv file to another using
different delimiter

Source code:
import csv
def copy_csv_data():
with open('Inputdata.csv')as F1:
with open('write_data_01.csv','w',newline='')as F2:
read=csv.reader(F1)
write=csv.writer(F2,delimiter='#')
for line in read:
write.writerow(line)
def display_copied_data():
with open('Write_data_01.csv')as F:
reader=csv.reader (F)
for data in reader:
print(data)
copy_csv_data()
display_copied_data()

Result:
The above program has been executed successfully
SEARCH AND DISPLAY USING BINARY FILE
EX.NO 14
Question
Write a python program to create a binary file to store member no. and
member name. Read member no and display its associated name else display
appropriate error message.
Aim
To create a binary file to store member no. and member name. Read member
no and display its associated name else display appropriate error message.
Program:

import pickle
Member={}
def store_binary_info():
with open ('member.dat','ab')as wbfile:
while True:
Mno=int(input('Enter the member no:'))
Name= input ('Enter the name:')
Member['Member No']= Mno
Member['Name']= Name
pickle.dump(Member , wbfile)
ch= input('Do you want to continue y/n')
if ch=='n':
print ('Binary file wariting is over')
break
def search_display_binary_info():
with open('member.dat','rb') as rbfile:
Mno=int(input('Enter the member no to be searched:'))
try:
while True:
Member=pickle.load(rbfile)
if Member['Member No']== Mno:
print(Member)
break
except EOFError:
print ('member no not found')
store_binary_info()
search_display_binary_info()
search_display_binary_info()

Result:
The above program has been executed successfully
MENU DRIVEN PROGRAM TO WRITE /READ/UPDATE/APPEND DATA ON TO
A BINARY FILE
EX. NO.15
Question
Write a program to create a menu driven program to write, read, update and
append data on to a binary file
Aim
To create a menu driven program to write, read, update and append data on to
a binary file
Program
import pickle
member={}
def w_bin():
with open('Membr.dat','wb')as wbfile:
while True:
m=int(input("Enter the member no:"))
name=input('Enter the name:')
member['MemberNo']=m
member['Name']=name
pickle.dump(member,wbfile)
ch=input('Do you want to contine y/n:') if
ch=='n':
print('Binary file writing is over')
break
def read_bin():
with open('member.dat','rb') as rrfile:
try:
while True:
member=pickle.load(rrfile)
print(member)
except EOFError:
rrfile.close()

def update_bin():
found=False
with open('member.dat','rb+') as rbfile:
try:
while True:
rpos=rbfile.tell()
member=pickle.load(rbfile)
if member['Name']=='Sundar':
member['Name']='Sundari'
rbfile.seek(rpos)
pickle.dump(member,rbfile)
print(member)
found=True
break
except EOFError:
if found==False:
print('Data not updated in the file') else:
print("Data updated succesfully")
def append_Bin():
with open('member.dat','ab') as wbfile:
while True:
mno=int(input("Enter the member no:"))
name=input('Enter the name')
member['Memberno']=mno
member['name']=name
pickle.dump(member,wbfile)
ch=input('Do yu want to continue y/n') if
ch=='n':
print('Binary file writing is over')
break
while True:
print('-----------------------------------------')
print('Menu Driven programming')
print('-----------------------------------------')
print('1.To create and store binary data')
print('2.To read binary data')
print('3.To update binary data')
print('4.To append data to the binary file')
print('5.To exit')
ch=int(input("Enter your choice"))
if ch==1:
w_bin()
elif ch==2:
read_bin()
elif ch==3:
update_bin()
elif ch==4:
append_Bin()
elif ch==5:
break

Result:
The above program has been executed
successfully
STACK OPERATION
EX.NO.16
Question
Write a program to implement a stack using a list
data structure.
Aim
To implement the stack operation using a list
data structure.
Program
stack=[]
def view():
for x in range(len(stack)):
print(stack[x])
def push():
item=int(input("Enter integer
value"))
stack.append(item)
def pop():
if(stack==[]):
print("Stack is empty")
else:
item=stack.pop(-1)
print("Deleted
element :",item)
def peek():
item=stack[-1]
print("Peeked
element :",item)
print("Stack operation")
print("***************")
print("1.Push")
print("2.View")
print("3.Pop")
print("4.Peek")
print("5.Exit")
while True:
choice=int(input("Enter your
choice"))
if choice==1:
push()
elif choice==2:
view()
elif choice==3:
pop()
elif choice==4:
peek()
elif choice==5:
break
else:
print("Wrong choice")

Result:
The above program has been executed
successfully
Ex. No 17
MYSQL Command - Exercise I
STATIONARY AND CONSUMER
Aim To create two table for stationary and consumer and execute the given
commands using MYSQL

Table : Stationary
S_ID STATIONARY_NA COMPANY PRICE
DP01 Dot pen ABC 10
PLO2 Pencil XYZ 6
ERO5 Eraser XYZ 7
PL01 Pencil CAM 5
GP02 Gel Pen ABC 15
Table: Consumer

C_ID CONSUMER_NAM CITY S_ID


01 RAJA DELHI PL01
06 RANI MUMBAI GP02
12 KAMALA DELHI DP01
15 VELLU DELHI PL02
16 BALA BANGALORE PL01

i) To display the details of those consumers whose Address is


ii)To display the details of stationary whose price is in the range of 8 to 15
(Both included) iii)To display the consumer Name, Address from table
consumer and company and price from table stationary with their
corresponding matching S_ID
iv)To increase the price of all stationary by 2
v)To display distinct company from STATIONARY

CREATE TABLE STATIONARY(S_ID CHAR(5) NOT NULL PRIMARY KEY,


STATIONARY_NAME CHAR(25), COMPANY CHAR(5), PRICE INT);

INERT INTO STATIONARY VALUES(‘DP01’,’DOT


PEN’,’ABC’,10) INERT INTO STATIONARY
VALUES(‘PL02’,’PENCIL’,’XYZ’,6) INERT INTO
STATIONARY VALUES(‘ERO5’,’ Eraser’,’XYZ’,7)
INERT INTO STATIONARY
VALUES(‘PL01’,’PENCIL’,’CAM’,5) INERT INTO
STATIONARY VALUES(‘GP02’,’GEL PEN’,’ABC’,15)

CREATE TABLE CONSUMER(C_ID VARCHAR(5),CONSUMER_NAME


VARCHAR(30), CITY CHAR(50), S_10 CHAR(5));
INERT INTO STATIONARY
VALUES(‘01’,’RAJA’,’DELHI’,’PL01’) INERT INTO
STATIONARY VALUES(‘06’,’RANI’,’MUMBAI’,10)
INERT INTO STATIONARY
VALUES(‘12’,’KAMALA’,’DELHI’,10) INERT INTO
STATIONARY VALUES(‘15’,’VELLU’,’DELHI’,10)
INERT INTO STATIONARY
VALUES(‘16’,’BALA’,’BANGALORE’,10)
EX. NO. 18
MYSQL Command - Exercise II
ITEM AND TRADERS
AIM: To create two tables for item and traders and execute the given
commands sing MYSQL

Table : ITEM

CODE INAME QTY PRICE COMPANY TCODE


1001 DIGITAL PAD 121 120 11000 XENTIA T01
1006 LED SCREEN 40 70 38000 SANTORA T02
1004 CAR GPS SYSTEM 50 2150 GEO KNOW T01
1003 DIGITAL CAMERA 160 8000 DIGICLICK T02
1005 PEN DRIVE 32GB 600 1200 STOREHOME T03
Table: TRADERS

TCODE TNAME CITY


T01 ELECTRONICS MUMBAI
T03 BUSY STORE DELHI
T02 DISP HOUSE INC CHANNAI

i) To display the details of all the items in ascending order of item


ii) names (i.e name) To display item name and price of all those items,
22000 (both values inclusive)
iii) To display the number of items, which are traded by each trader. The
expected output of this query should be
T01 2
T02 2
T03 1
iv) To display the price , item name (i.e Iname) and quantity (ie Qty) of
those items which have quantity more than 150
v) To display the price names of those traders, who are either from
DELHI or from MUMBAI

CREATE TABLE ITEM(CODE INT, INAME CHAR(35),QTY INT, PRICE INT,


COMPANY CHAR(25),TCODE CHAR(5));

INERT INTO ITEM VALUES(1001,’DIGITAL PAD


121’,120,11000,’XENTIA’,’T01’) INERT INTO ITEM
VALUES(1006,’LED SCREEN 40’,70,38000,’SANTORA’,’T02’) INERT
INTO ITEM VALUES(1004,’CAR GPS SYSTEM’,50,2150,’GEO
KNOWN’,’T01’) INERT INTO ITEM VALUES(1003,’DIGITAL CAMERA
12X’,160,8000,’DIGICLICK’,’T02’) INERT INTO ITEM
VALUES(1005,’PEN DRIVE 32GP’,600,1200,’STORE HOME’,’T03’)

CREATE TABLE TRADERS(TCODE CHAR(5), TNAME CHAR(25),CITY CHAR(20));

INERT INTO TRADERS VALUES(‘T01’,ELECTRONIC


SALES’,’MUMBAI’) INERT INTO TRADERS
VALUES(‘T03’,BUSY STORE CORP’,’DELHI’) INERT
INTO TRADERS VALUES(‘T02’,DISP HOUSE
INC’,’CHENNAI’)
EX. NO. 19
MYSQL COMMAND - EXERCISE III
DOCTOR AND SALARY
Aim : To create two table for doctor and salary and execute the given
commands using MYSQL

TABLE : DOCTOR
ID NAME DEPT SEX EXPERIENCE
101 John ENT M 12
104 SMITH ORTHOPEDIC M 5
107 GEORGE CARDIOLOGY M 10
114 LARA SKIN F 3
109 K GEORGE MEDICINE F 9
105 JOHNSON ORTHOPEDIC M 10
117 LUCY ENT F 3
111 BILL MEDICINE M 12
130 MORPHY ORTHOPEDIC M 15
TABLE : SALARY

ID BASIC ALLOWANCE CONSULTATIO


101 12000 1000 300
104 23000 2300 500
107 33000 4000 500
114 12000 5200 100
109 42000 1700 200
105 18900 1690 300
130 21700 2600 300
i) Display name of all doctors who are in “MEDICINE” having more than
from table DOCTOR
ii) Display the average salary of all doctors working in “ENT”
department using the tables DOCTOR and SALARY (salary=basic +
allowance)
iii) Display minimum Allowance of female doctors
iv) Display doctor id, name from the table salary with their
corresponding matching ID v) To display distinct department from the
table doctor

CREATE TABLE DOCTOR(ID IN NOT NULL PRIMARY KEY, NAME CHAR25),DEPT


CHAR(25), GENDER CHAR , EXPERIENCE INT);

INERT INTO DOCTOR


VALUES(101,’JOHN’,’ENT’,’M’,12)
INERT INTO DOCTOR
VALUES(104,’SMITH’,’ORTHOPEDIC’,’M’,5)
CREATE TABLE SALARY(id in NOT NULL PRIMARY KEY, BASIC INT,
ALLOWANCE INT, CONSLATION INT);

INERT INTO SALARY


VALUES(101,12000,1000,300); INERT
INTO SALARY
VALUES(104,23000,2300,500);
EX. NO. 20
MYSQL Command - Exercise IV
COMPANY AND CUSTOMER
Aim : To create two table for CAMPANY and CUSTOMER and execute the given
commands using MYSQL

TABLE: COMPANY
CID NAME CITY PRODUCT NAME
111 SONY DELHI TV
222 NOKIA MUMBAI MOBILE
333 ONIDA DELHI TV
444 SONY MUMBAU MOBILE
555 BLACK BERRY MADRAS MOBILE
666 DELL DELHI LAPTOP

TABLE : CUSTOMER

CUSTID NAME PRICE QTY CID


101 ROHAN 70000 20 222
102 DEEPAK 50000 10 666
103 MOHAN 30000 5 111
104 SAHIL ABNSAL 35000 3 333
105 NEHA SONI 25000 7 444
106 SONAL 20000 5 333
AGGARW
107 ARUN SINGH 50000 15 666

I) To display those company name which are having price less


II) than 30000 To display the name of the companies in reverse
III) alphabetical order
To increase the price by 1000 for those customer whose

CREATE TABLE COMPANY(CID IN(3), NAME VARCHAR(15), CITY VARCHAR(10),


PRODCTNAME VARCHAR(15));

INSERT INTO COMPANY VALUES(111,’SONA’,’DELHI’,’TV’);

CREATE TABLE CUSTOMER(CUSTID IN(3), NAME VARCHAR(15), PRICE INT,QTY INT,


CID INT);

INSERT INTO CUSTOMER VALUES(101,’ROHAN SHARMA’,70000,20,222)


EX. NO. 21
MYSQL Command - Exercise V
Teacher
Aim : To create two table for teacher and execute the given
commands using MYSQL

TABLE : TEACHER

NO NAME AGE DPARTMENT DATE SALARY SEX


OF JOIN
1 Jishnu 40 Physics 10/01/97 40000 M
2 Lalitha 36 Maths 24/03/98 50000 F
3 Kamala 34 Chemistry 12/2/95 50000 F
4 Rani 29 Maths 01/07/99 40000 F
5 Ragu 45 Computer 27/02/2001 35000 M
6 Shiva 41 Physics 25/02/97 43000 M
7 Janaki 37 Maths 31/07/95 55000 F
8 Kasthuri 30 chemistry 31/07/95 36000 F

i) To show all information about the teacher of history


ii) department
iii)To list the names of female teacher who ae in Maths
department To list names of all teachers with their date of
iv) joining in ascending order To count the number of teachers
CREATE TABLE TEACHER(N0 INT(2), NAME VARCHAR(15), AGE INT(3), DEPARTMENT
VARCHAR(15), DATEOFJOIN VARCHAR(15), SALARY INT(7), SEX CHAR(1));

INSERT INTO TEACHER VALUES(1,’JISHNU’,40,’PHYICS’,’10/01/97’,12000,’M’)


Ex.no 22
INTEGRATE PYTHON WITH MYSQL – FETCHING RECORDS FROM TABLE
AIM:
To integrate MSQL with python by importing the mysql module and extracting data
from result set

Source code

import mysql.connector as mysqltor


mycon=mysqltor.connect(host='localhost', user='root' ,passwd='root', database='emp')
if mycon.is_connected()==False:
print("Error connecting to Mysql database")
cur=mycon.cursor()
cur.execute("select empno,ename,job from empl")
data=cur.fetchall()
count=cur.rowcount
for row in data:
print(row)
mycon.close()

Result
The above program has been executed and verified successfully.
Ex.no 23
INTEGRATE PYTHON WITH MYSQL – COUNTING RECORDS FROM TABLE
AIM:
To integrate MSQL with python by importing the MYSQL module and extracting data
from result set
SOURCE CODE:

import mysql.connector as mysqltor


mycon=mysqltor.connect(host='localhost', user='root' ,passwd='root', database='emp')
if mycon.is_connected()==False:
print("Error connecting to Mysql database")
cur=mycon.cursor()
cur.execute("select * from empl")
data=cur.fetchone()
count=cur.rowcount
print("Total number of rows retrieved from rsult set:",count)
data=cur.fetchone()
count=cur.rowcount
print("Total number of rows retrieved from rsult set:",count)
data=cur.fetchmany(3)
count=cur.rowcount
mycon.close()
print("Total number of rows retrieved from rsult set:",count)

Result
The above program has been executed and verified successfully.
Ex.no 24
INTEGRATE PYTHON WITH MYSQL – SEARCHING A RECORD FROM TABLE
AIM:
To integrate MSQL with python by importing the MYSQL module to search an
employee using Employee Number, if it is present in table display the record
SOURCE CODE:

import mysql.connector as mysqltor


mycon=mysqltor.connect(host='localhost', user='root' ,passwd='root', database='emp')
if mycon.is_connected()==False:
print("Error connecting to Mysql database")
eno=int(input("Enter Employee Number"))
cur=mycon.cursor()
cur.execute("select * from empl")
data=cur.fetchall()
avail=0
for row in data:
if row[0]==eno:
avail=1
print(row)
else:
if avail==0:
print("Invalid Employee No.")
mycon.close()

Result
The above program has been executed and verified successfully.
Ex.no 25
INTEGRATE PYTHON WITH MYSQL – DELETING A RECORD FROM TABLE
AIM:
To integrate MSQL with python by importing the MYSQL module to search a
student using roll number, if it is present in table delete the record
SOURCE CODE
import mysql.connector as mysqltor
mycon=mysqltor.connect(host='localhost',
user='root' ,passwd='root', database='Student')
if mycon.is_connected()==False:
print("Error connecting to Mysql database")
cur=mycon.cursor()
cur.execute("select * from stu_per")
data=cur.fetchall()
for row in data:
print(row)
print()
sno=int(input("Enter Student No. Which you want to delete"))
delete=0
for row in data:
if row[0]==sno:
delete=1
cur.execute("delete from stu_per where stu_no={}".format(sno))
mycon.commit()
print()
if delete==1:
print("Your Record deleted successfully")
else:
print("Invalid Student No")
print()
cur.execute("select * from stu_per")
data=cur.fetchall()
for row in data:
print(row)
mycon.close()

Result
The above program has been executed and verified successfully.

You might also like