0% found this document useful (0 votes)
16 views29 pages

exp21_exp23 (11 files merged)

Uploaded by

msrikar328
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)
16 views29 pages

exp21_exp23 (11 files merged)

Uploaded by

msrikar328
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
You are on page 1/ 29

21.

Write a program to connect Python with MYSQL using database connectivity for the table
SALES given below and perform the following.

NAME PRODUCT QTY_TAR PRICE COMMISSION

Santhosh Lux 50 15.35 120


Praveen Harpic 25 40.25 150
Kumar Britannia 20 11.25 100
Arjun Glaxo 30 67.85 150
Jacob Hamam 40 11.50 200

1. Display all the records of those QTY_TAR is more than 35 and arranged by ascending order of product.

2. Select the name and product where the product as Britannia and the commission>=100

3. To display the number of tuples available in the table.

4. Select and display the maximum price and minimum price of the table sales.

5. Delete the record whose commission is 150.

1
Exp21.PROGRAM :

import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='root',charset='utf8')
cur=con.cursor()

cur.execute("create database if not exists practical")


cur.execute("use practical")
cur.execute("create table if not exists sales(Name char(20) not null, product char(10), Qty_tar int, price
double, commission int)")
print("Table created")

cur.execute("insert ignore into sales values('Santhosh','Lux',50,15.35,120)")


cur.execute("insert ignore into sales values('Praveen','Harpic',25,40.25,150)")
cur.execute("insert ignore into sales values('Kumar','Britannia',20,11.25,100)")
cur.execute("insert ignore into sales values('Arjun','Glaxo',30,67.85,150)")
cur.execute("insert ignore into sales values('Jacob','Hamam',40,11.50,200)")

con.commit()
print("Records inserted")

print("1.")
cur.execute("select * from SALES where QTY_TAR>35 order by PRODUCT ")
for x in cur:
print(x)
print("2.")
cur.execute(" select NAME, PRODUCT from SALES where PRODUCT ='Britannia' and
COMMISSION>=100")
for x in cur:
print(x)
print("3.")
cur.execute("select count(*) from SALES ")
for x in cur:
print(x)
print("4.")
cur.execute("select max(price), min(price) from SALES")
for x in cur:
print(x)
print("5.")
cur.execute("delete from sales where commission=150")
print("Record Deleted")

con.commit()
cur.close()
con.close()

2
OUTPUT:

Table created
Records inserted
1.
('Jacob', 'Hamam', 40, 11.5, 200)
('Santhosh', 'Lux', 50, 15.35, 120)
2.
('Kumar', 'Britannia')
3.
(5,)
4.
(67.85, 11.25)
5.
Record Deleted

3
22.Write a program to connect Python with MYSQL using database connectivity for the table
MOVIE given below and perform the following.

TITLE TYPE RATING STARS QTY PRICE

Liar Liar Comedy PG13 Jim Carre 5 25.35


Lost World Horror PG Melgibson 4 35.45
The specialist Action G Stallon 3 40.23
Down Periscope Comedy PG13 Stone 6 43.25
Conair Action G Nicholas 3 55.25

1. Display the maximum price from movie table.

2. List all the stars name starts with ‘S’.

3. Display all the details arranged by ascending order of title.

4. Display the title where price is more than 20.

5. To change the value of quantity as 10 those movie type is comedy.

4
Exp.23. PROGRAM:
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='root',charset='utf8')
cur=con.cursor()

cur.execute("create database if not exists practical")


cur.execute("use practical")

cur.execute("create table if not exists movie (title char(20) primary key, type char(10), rating char(15), stars
char(10), qty int, price float)")
print("Table created")

cur.execute("insert ignore into movie values('Liar Liar','Comedy','PG13','JimCarre',5,25.35)")


cur.execute("insert ignore into movie values('Lost World','Horror','PG','Melgibson',4,35.45)")
cur.execute("insert ignore into movie values('The specialist','Action','G','Stallon',3,40.23)")
cur.execute("insert ignore into movie values('Down Periscope','Comedy','PG13','Stone',6,43.25)")
cur.execute("insert ignore into movie values('Conair','Action','G','Nicholas',3,55.25)")
con.commit()
print("Records inserted")

print("1.")
cur.execute("select max(price) from movie")
for x in cur:
print(x)

print("2.")
cur.execute("select stars from MOVIE where STARS like 'S%'")
for x in cur:
print(x)

print("3.")
cur.execute("select * from MOVIE order by TITLE ")
for x in cur:
print(x)
print("4.")
cur.execute("select TITLE from MOVIE where PRICE>20")
for x in cur:
print(x)

print("5.")
cur.execute("update movie set qty=10 where type='comedy' ")
print("Record updated")
con.commit()
cur.close()
con.close()

5
OUTPUT:

Table created
Records inserted
1.
(55.25,)
2.
('Stone',)
('Stallon',)
3.
('Conair', 'Action', 'G', 'Nicholas', 3, 55.25)
('Down Periscope', 'Comedy', 'PG13', 'Stone', 10, 43.25)
('Liar Liar', 'Comedy', 'PG13', 'Jim Carre', 10, 25.35)
('Lost World', 'Horror', 'PG', 'Melgibson', 4, 35.45)
('The specialist', 'Action', 'G', 'Stallon', 3, 40.23)
4.
('Conair',)
('Down Periscope',)
('Liar Liar',)
('Lost World',)
('The specialist',)
5.
Record updated

6
23.Write a program to connect Python with MYSQL using database connectivity for the table
LIBRARY given below and perform the following.

BID TITLE AUTHOR TYPE PUB QTY PRICE

101 Data structure Lipchutz DS McGraw 4 217


102 Advanced Pascal Schildt PROG BPB 5 350
103 Mastering C++ Gurewich PROG PHI 3 130
104 Mastering Window Cowart OS BPB 6 40
105 Network Guide Freed NET Zpress 5 200

1. Display all the details of those type is PROG and publisher is BPB.

2. Display all the details with price more than 130 and arranged by ascending order of qty.

3. Display the number of books published by BPB.

4. Display the title and qty for those qty between 3 and 5.

5. Delete the record whose type is PROG.

7
PROGRAM:
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='root',charset='utf8')
cur=con.cursor()
cur.execute("create database if not exists practical")
cur.execute("use practical")
cur.execute("create table if not exists library (bid int primary key, title char(20) not null ,author char(10),
type char(10), pub char(10), qty int, price int)")
print("Table created")

cur.execute("insert ignore into library values(101,'Data structure','Lipchutz','DS','McGraw',4,217)")


cur.execute("insert ignore into library values(102,'AdvancedPascal','Schildt','PROG','BPB',5,350)")
cur.execute("insert ignore into library values(103,'Mastering C++','Gurewich','PROG','PHI',3,130)")
cur.execute("insert ignore into library values(104,'Mastering Window','Cowart','OS','BPB',6,40)")
cur.execute("insert ignore into library values(105,'Network Guide','Freed','NET','Zpress',5,200)")

con.commit()
print("Records inserted")

print("1.")
cur.execute("select * from library where TYPE='PROG' and PUB ='BPB' ")
for x in cur:
print(x)

print("2.")
cur.execute("select * from library where PRICE>130 order by QTY ")
for x in cur:
print(x)

print("3.")
cur.execute("select count(*) from library where PUB='BPB' ")
for x in cur:
print(x)

print("4.")
cur.execute("select title,qty from library where qty between 3 and 5")
for x in cur:
print(x)

print("5.")
cur.execute("delete from library where type='PROG' ")
print("Record deleted")
con.commit()
cur.close()
con.close()

8
OUTPUT:

Table created
Records inserted
1.
(102, 'Advanced Pascal', 'Schildt', 'PROG', 'BPB', 5, 350)
2.
(101, 'Data structure', 'Lipchutz', 'DS', 'McGraw', 4, 217)
(102, 'Advanced Pascal', 'Schildt', 'PROG', 'BPB', 5, 350)
(105, 'Network Guide', 'Freed', 'NET', 'Zpress', 5, 200)
3.
(2,)
4.
('Data structure', 4)
('Advanced Pascal', 5)
('Mastering C++', 3)
('Network Guide', 5)
5.
Record deleted

*****

9
Exp:13

Heading: TAYLOR’S SERIES AND SIMULATING A DICE

To write a menu driven program to compute the sin value using Taylor’s series
expansion and simulating a Dice using random number.

[Taylor’s series: x – x3+ x5 - x7 + …..]


3! 5! 7!

PROGRAM:
import math

import random

def fact(q):

f =1

for i in range(1,q+1):

f=f*i

return f

#Sin Series – Taylor’s series

def sintaylor(x):

sum = 0

sign = 1

for i in range(1,x+1,2):

term = ((x**i)/fact(i))*sign

sum = sum + term

sign = sign * -1

print("The result of the series=",sum)


def dice():

ch = int (input("Enter 0 to Main menu and 1 Roll the dice:"))

while ch ==1:

print("The number for you is..."d)

x = random.randint(1,6)

print(x)

ch = int (input("Enter 0 to Main menu and 1 Roll the dice:"))

#main

while True:

print("Main menu")

print("1.Sin Series – Taylor’s series")

print("2.Simulate a dice")

print("3.exit")

choice=int(input("enter your choice:"))

if choice==1:

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

radians = (math.pi/180)* n

sintaylor(radians)

if choice==2:

dice()

if choice==3:

break
RESULT:

Main menu

1.Sin Series – Taylor’s series

2.Simulate a dice

3.exit

enter your choice:1

Enter the value of n in degrees:90

The result of the series= 1.0000000000000002

Main menu

1.Sin Series – Taylor’s series

2.Simulate a dice

3.exit

enter your choice:2

Enter 0 to Main menu and 1 Roll the dice:1

The number for you is...

Enter 0 to Main menu and 1 Roll the dice:0

Main menu

1.Sin Series – Taylor’s series

2.Simulate a dice

3.exit

enter your choice:3


Exp 15
Heading
INTEGRATE PYTHON WITH MYSQL – SEARCH & UPDATE

To integrate SQL with Python by importing the MYSQL module to search an


employee using empno Update the record and display the updated records.

import mysql.connector
con=mysql.connector.connect(host="localhost",user='root',password="bvm",
database="employee")
cur=con.cursor()
print("BEFORE UPDATION")
cur.execute("select * from empl")
data=cur.fetchall()
for i in data:
print(i)
query="Update empl set Ename='Sumita' where Eno=2"
cur.execute(query)
con.commit()
print("Rows updated successfully")
print("Displaying the records after updating...")
cur.execute("select * from empl ")
data=cur.fetchall()
for i in data:
print(i)
Exp 16
Heading:
INTEGRATE PYTHON WITH MYSQL – DELETE A RECORD

To integrate SQL with Python by importing the MYSQL module to search an


employee using empno and delete the record.

import mysql.connector
con=mysql.connector.connect(host="localhost",user='root',password="bvm",
database="employee")
cur=con.cursor()
print("BEFORE DELETION")
cur.execute("select * from empl")
data=cur.fetchall()
for i in data:
print(i)

temp=int(input("Enter the Roll number to Delete:"))


query="DELETE FROM EMPL WHERE ENO=" + str(temp) + ";"
cur.execute(query)
con.commit()
print("Row deleted successfully")
print("Displaying the records after delete...")
cur.execute("select * from empl")
data=cur.fetchall()
for i in data:
print(i)
Exp 12:
Heading- GAMES -DICTIONARY

Write a program to create a dictionary with game as key and list with elements like player name,
country name and points for N players and write functions for the followings
i. To arrange the players in alphabetical order of game and print the same
ii. Accept a country name and print the details of players
iii. Accept a game and update the points by 15% of existing points and display the updated
records

def INPUT(d,n):
for i in range(n):
game=input("Enter the game:")
p=list()
p.append(input("Enter player name:"))
p.append(input("Enter Country name:"))
p.append(int(input("Enter the points:")))
d[game]=p
print('-'*70)

def SHOW(d,n):
print("\nRecords in Ascending order of Game:")
for k in sorted(d,reverse= False):
print(k,d[k])
print('-'*70)

def SEARCH(d,n,coun):
flag=0
for key in d.keys():
if d[key][1]==coun:
print(key,d[key])
flag+=1
if flag==0:
print("Searching country not found")
print('-'*70)

def MODIFY(d,n,game):
flag=0
for key in d.keys():
if key==game:
d[key][2]+=d[key][2]*.15
flag+=1
if flag==0:
print("Searching country not found")
else:
Exp 12(contd…)
print(flag, "Records updated")
print('-'*70)

def main():
d=dict()
n=int(input("How many Games:"))
INPUT(d,n)
SHOW(d,n)
coun=input("Enter country name to be searched:")
SEARCH(d,n,coun);
game=input("Enter game name to increase the points:")
MODIFY(d,n,game)
print("Records after updation:")
SHOW(d,n)
main()
-------------------------------------------------------------------------------------------
RESULT:
How many Games:3
Enter the game:chess
Enter player name:Viishnu
Enter Country name:India
Enter the points:5456
Enter the game:Cricket
Enter player name:Dhoni
Enter Country name:India
Enter the points:7777
Enter the game:Hockey
Enter player name:Dhanraj pillay
Enter Country name:India
Enter the points:9934
----------------------------------------------------------------------

Records in Ascending order of Game:


Cricket ['Dhoni', 'India', 7777]
Hockey ['Dhanraj pillay', 'India', 9934]
chess ['Viishnu', 'India', 5456]
----------------------------------------------------------------------
Enter country name to be searched:India
chess ['Viishnu', 'India', 5456]
Cricket ['Dhoni', 'India', 7777]
Hockey ['Dhanraj pillay', 'India', 9934]
----------------------------------------------------------------------
Enter game name to increase the points:chess
1 Records updated
----------------------------------------------------------------------
Exp 12(contd…)
Records after updation:

Records in Ascending order of Game:


Cricket ['Dhoni', 'India', 7777]
Hockey ['Dhanraj pillay', 'India', 9934]
chess ['Viishnu', 'India', 6274.4]
----------------------------------------------------------------------
Exp14
Heading-
INTERFACE SQL WITH PYTHON – CREATE TABLE , INSERT COMMANDS
To integrate Python with MySQL to create a table , insert the records in to the table
and to display them.

import mysql.connector
con=mysql.connector.connect(host="localhost",user='root',password="bvm",
database="employee")
cur=con.cursor()
cur.execute("Create table EMPL(Eno int,Ename varchar(10),Esal float)")
print("table created successfully:")
cur=con.cursor()
while True:
Eno=int(input("Enter Employee Number :"))
Name=input("Enter Employee Name:")
salary=float(input("Enter Employee Salary:"))
query="Insert into empl values({},'{}',{})".format(Eno,Name,salary)
cur.execute(query)
con.commit()
print("row inserted successfully...")
ch=input("Do You Want to enter more records?(y/n)")
if ch=="n":
break
cur.execute("select * from empl")
data=cur.fetchall()
for i in data:
print(i)
print("Total number of rows retrieved=",cur.rowcount)
---------------------------------------------------------------------------------------------------
RESULT:

table created successfully:


Enter Employee Number :1
Enter Employee Name:ratha
Enter Employee Salary :5000
row inserted successfully...
Do You Want to enter more records?(y/n)y
Enter Employee Number :2
Enter Employee Name:kumar
Enter Employee Salary :10000
row inserted successfully...
Do You Want to enter more records?(y/n)n
(1, 'ratha', 5000.0)
(2, 'kumar', 10000.0)
Total number of rows retrieved= 2
Exp 14(contd…)

>>>
Exp11:

Heading: VOWEL,CONSONANT AND PALINDROME STRING COUNTING

Write a function that accept N string values one by one, Count and print number of
palindrome strings, number of vowel strings( string starts with vowel character) and of
consonant strings( string starts with consonant character).

def PALIND(s):

a=""

for i in range(len(s)-1,-1,-1):

a+=s[i]

if s==a:

return 1

else:

return 0

def CHECK(s):

vow="aeiouAEIOU"

if s.isalpha():

if s[0] in vow:

return 'v'

else:

return 'c'
n=int(input("How many strings?"))

p=v=c=0

print("Enter ", n, " Strings:")

for i in range(n):

a=input()

if PALIND(a)==1:

p+=1

res=CHECK(a)

if res=='v':

v+=1

elif res=='c':

c+=1

print("\n Number of palindrome strings:",p)

print("\n Number of vowel strings:",v)

print("\n Number of consonent strings:",c)

RESULT:

How many strings?5

Enter 5 Strings:

madam

racecar

Orange
apple

chennai

Number of palindrome strings: 2

Number of vowel strings: 2

Number of consonent strings: 3


Exp 17:

Write a function that accepts an integer list as argument and shift all odd numbers to the left
and even numbers to the right of the list without changing the order.

eg. List before shifting: [12,15,10,5,8,9]


List after shifting : [15, 5, 9, 12, 10, 8]

def SHIFT(a,n):
c=0
for i in range(n):
if a[i]%2!=0:
x=a.pop(i)
a.insert(c,x)
c+=1

a=[]
n=int(input("How many values:"))
print("Enter ",n," values:")
for i in range(n):
a.append(int(input()))
print("List values before shifting:",a )
SHIFT(a,n)
print("List values after shifting:",a )

OUTPUT:
How many values:6
Enter 6 values:
12
15
10
5
8
9
List values before shifting: [12, 15, 10, 5, 8, 9]
List values after shifting: [15, 5, 9, 12, 10, 8]
Exp 18
Write a function create() to create password.csv which accepts user id
and password. Write function show() to display all the details,
search() to accept the user id and print the password if the user id is
present otherwise print the error message 'user id is not present”

import csv def


create():
f=open("password.csv",'w',newline="")
writer=csv.writer(f) writer.writerow(["User
Name",'Password']) while True:
r=input("Enter the User id:")
n=input("Password:") data=[r,n]
writer.writerow(data)
ch=input("press any key to continue?N to exit\n") if ch
in 'nN':
break
f.close()

def show():
f=open("password.csv",'r')
reader=csv.reader(f)
for a in reader:
print(a[0],'\t',a[1]) f.close()

def search():
f=open("password.csv",'r')
id=(input("Enter the User id to search password:")) reader=csv.reader(f)
for a in reader:
if a[0]==id: print("Password
:",a[1]) break
else:
print("User id is not present")
f.close()

create()
show()
search()
OUTPUT

Enter the User id:covid2019


Password:corona
press any key to continue?N to exit
y
Enter the User id: Italy 2017
Password: Venice
press any key to continue?N to exit
n
User Name Password
covid2019 corona
Italy 2017 Venice
Enter the User id to search password: Italy 2017
Password : Venice
Exp.20

Write a function that accept N strings in a tuple as argument, Find and print the longest and shortest
string of N strings (Lengthwise). Also find and print the greatest and smallest string of N strings
(Alphabetical order) along with main program.

PROGRAM:
def FIND_LONG_SHORT(s,n):
long=short=s[0]
for a in s:
if len(a)>len(long):
long=a
elif len(a)<len(short):
short=a
print("Longest string is:",long) ;
print("Shortest string is:",short)

def FIND_GREAT_SMALL(s,n):
great=small=s[0]
for a in s:
if a>great:
great=a
elif a<small:
small=a
print("Greatest string is:",great)
print("Smallest string is:",small)

t=()
n=int(input("How many strings:"))
print("Enter ", n ," Strings:")
for i in range(n):
t+=(input(),)
FIND_LONG_SHORT(t,n)
FIND_GREAT_SMALL(t,n)
OUTPUT:
How many
strings:5 Enter
5 Strings:
CHENNAI
THIRUVANANATHAPU
RAM GOA
PUNE
VIJAYAWAD
A
Longest string is: THIRUVANANATHAPURAM
Shortest string is: GOA
Greatest string is: VIJAYAWADA
Smallest string is: CHENNAI
EXP 19

A binary file “emp.dat” has structure [empno, empname,salary]. Write a user defined
function CreateEmp() to input data for a record and add to emp.dat . Also write a function
DELETE() to accept an employee number and delete the details. Function should display the
file contents before and after deletion of employee record using DISPLAY() function.

import pickle
def validate_empno():
with open("emp.dat",'rb') as f:
en=int(input("Enter emp no."))
try:
while True:
a = pickle.load(f)
if en == a[0]:
print("\nEmp no. is already exists!!!")
return -1
except EOFError:
return en
def CreateEmp():
f=open("emp.dat",'wb')
n=int(input("Enter how many employees"))
for i in range(n):
lis=[]
eno=validate_empno()
if eno==-1:
break
ename=input("Enter employee name")
salary=int(input("Enter basic salary"))
lis=[eno,ename,salary]
pickle.dump(lis,f)
f.flush()
f.close()

def DISPLAY():
with open("emp.dat",'rb') as f:
print("\nContents of the file")
print("\nEMPNO\tEMPNAME\tSALARY")
try:
while True:
a = pickle.load(f)
print(a[0],a[1],a[2],sep='\t')
except EOFError:
return
def DELETE():
import os
flag=0
en=int(input("Enter the emp no. to delete"))
with open("emp.dat",'rb') as f, open("tem.dat",'wb') as f2:
try:
while True:
a = pickle.load(f)
if en != a[0]:
pickle.dump(a,f2)
f2.flush()
else:
flag=1
except EOFError:
pass
if flag==0:
print("\nEmp no. is not found!")
return
else:
print("\nRecord is deleted!")
os.remove('emp.dat')
os.rename('tem.dat','emp.dat')

CreateEmp()
DISPLAY()
DELETE()
print("\nAfter Delete")
DISPLAY()

OUTPUT:
Enter how many employees3
Enter emp no.10
Enter employee namearun
Enter basic salary12000
Enter emp no.20
Enter employee namekumar
Enter basic salary8000
Enter emp no.30
Enter employee nameshyam
Enter basic salary14000
Contents of the file
EMPNO EMPNAME SALARY
10 arun 12000
20 kumar 8000
30 shyam 14000
Enter the emp no. to delete20

Record is deleted!
After Delete
Contents of the file

EMPNO EMPNAME SALARY


10 arun 12000
30 shyam 14000

You might also like