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

Practical File

Uploaded by

Piyush Jain
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)
39 views

Practical File

Uploaded by

Piyush Jain
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/ 57

Module of 20 functions

# 1. To calculate area of circle


def areac(r):
a=r*r*3.14
return a
# 2. To calculate volume of a sphere
def volsph(r):
v=r*r*r*(4/3)*3.14
return v

# 3. To check for the passed character is a vowel


or not
def isvowel(s):
if s in "AaEeIiOoUu":
return True
else:
return False

# 4. To calculate simple interest


def SI(p,r,t):
I=(p*r*t)/100
return I

# 5. To calculate volume of a cylinder


def volcylinder(r,h):
v=r*r*h*3.14
return v

Page 1 of 57
# 6. To check whether the string is palindrome
or not
def pal(x):
y=''
for i in range(len(x)-1,-1,-1):
y=y+x[i]
if x==y:
return "palindrome"
else:
return "not palindrome"

# 7. To check for armstrong number


def armst(x):
s=0
r=x
while (r>0):
d=r%10
s+=d**3
r//=10
if x==s:
return "Armstrong number"
else:
return "not an armstrong number"

# 8. To find sum of series


def sumseries(x,n):
s=0
for i in range(1,n+1):
f=1
for j in range(1,i+1):
f=f*j
s=s+(x**(2*i-1))/f
return s
fxd fcyj gukxn rgds12

Page 2 of 57
# 9. To convert celcius to fahrenheit
def conv(x):
F=((9/5)*x)+32
return F

# 10. To pass and check a number


def numcheck(x):
if x>0:
return "1"
elif x<0:
return "0"

# 11. To display biggest number in list


def blist(x):
s=x[0]
d=x[0]
for i in x:
if s<i:
s=i
return s

# 12. To arrange list in ascending order using


bubble sort
def ascen(L):
for i in range(0,len(L)):
for j in range(0,len(L)-1-i):
if L[j]>L[j+1]:
L[j],L[j+1]=L[j+1],L[j]
return L

Page 3 of 57
# 13. To arrange list in ascending order using
insertion sort
def insert(L):
for i in range (1,len(L)):
t=L[i]
j=i-1
while t<L[j] and j>=0:
L[j+1]=L[j]
j=j-1
L[j+1]=t
return L

# 14. To display smallest in tuple


def tupsm(T):
S=T[0]
for i in T:
if S>i:
S=i
return S

# 15. Sum of diagonal elements in 2-D list


def tdsum(l):
s=s1=0
r=len(l)
for i in range(r):
s=s+l[i][i]
s1+=l[i][len(l)-1-i]
return s,s1

# 16. To pass a string and reverse it


def revstr(a):
y=''
for i in range(len(a)-1,-1,-1):
y+=a[i]
return y
Page 4 of 57
# 17. To pass a string and swap its case
def swap(s):
a=''
for i in s:
if i.islower():
a=a+i.upper()
elif i.isupper():
a=a+i.lower()
else:
a=a+'#'
return a

# 18. To pass a integer and reverse it


def revnum(n,rn):
while(n):
rem=n%10
rn=rn*10+rem
n//=10
print("reversed number =",rn)

# 19. To pass a name and print it in desired format


def pattern(n):
for i in range(len(n)+1):
print(n[0:i])

# 20. To create dictionary of frequencies of letters and digits in


string
def dict1(n):
d={}
for i in n:
if i not in d.keys():
d[i] = 1
else:
d[i] +=1
print(d)
Page 5 of 57
Calling functions
import practical
# 1. To calculate area of circle
x=int(input("enter the radius of circle"))
print("area of circle-",practical.areac(x))

# 2. To calculate volume of a sphere


x=int(input("enter the radius of sphere"))
print("volume of sphere=",practical.volsph(x))

# 3. To check for the passed character is a vowel or not


x= input("enter the letter to check for vowel or not")
print(practical.isvowel(x))

# 4. To calculate simple interest


p=int(input("enter the principal"))
r=int(input("enter the rate"))
t=int(input("enter the time"))
print("Simple Interest=",practical.SI(p,r,t))

# 5. To calculate volume of a cylinder


r=int(input("enter the radius of cylinder"))
h=int(input("enter the height of cylinder"))
print("volume of cylinder=",practical.volcylinder(r,h))

# 6. To check whether the string is palindrome or not


x=input("enter the string to check for palindrome")
print(practical.pal(x))

# 7. To check for armstrong number


x=int(input("enter the number to check for armstrong no."))
print("numbertype=",practical.armst(x))

Page 6 of 57
# 8. To find sum of series
x=int(input("enter the numerator"))
n=int(input("enter the length"))
print("sum=",practical.sumseries(x,n))

# 9. To convert celcius to fahrenheit


C=float(input("enter the temp. in celcius"))
print("Fahrenheit temp.=",practical.conv(C))

# 10. To pass and check a number


x=int(input("enter the number"))
print(practical.numcheck(x))

# 11. Display biggest number in list


L=eval(input("enter the list"))
print("biggest number=",practical.blist(L))

# 12. Arrange list in ascending order using bubble sort


L=eval(input("enter the list"))
print("ascending order=",practical.ascen(L))

# 13. Arrange list in ascending order using insertion sort


L=eval(input("enter the list"))
print("sorted list=",practical.insert(L))

# 14. Smallest in tuple


T=eval(input("enter the tuple"))
print("smallest number=",practical.tupsm(T))

# 15. Sum of diagonal elements in 2-D list


l=[]
r=int(input("enter no. of rows"))
c=int(input("enter no. of columns"))
for i in range(r):
row=[]

Page 7 of 57
for j in range(c):
y=int(input("enter the number"))
row.append(y)
l.append(row)
s,s1=practical.tdsum(l)
print("sum of diagonal 1=",s)
print("sum of diagonal 2=",s1)

# 16. To pass a string and reverse it


a=input("enter a string")
print("reversed string : ",practical.revstr(a))

# 17. To pass a string and swap its case


s=input("enter a string to swap its case : ")
print("string after swapping case :",practical.swap(s))

# 18. To pass a integer and reverse it


n=int(input("enter a number to be reversed : "))
rn=0
practical.revnum(n,rn)

# 19. To pass a name and print it in desired format


x=input("enter a string to print in desired format")
practical.pattern(x)

# 20. To create dictionary of frequencies of letters and digits in string


x=input("enter a string to display frequency of letters : ")
practical.dict1(x)

Page 8 of 57
output

Page 9 of 57
Page 10 of 57
Page 11 of 57
# File handling

Notes.txt
Text File: A text file stores information in the form of a
stream of ASCII or Unicode characters. In text file, each line
of text is terminated, with a special character known as end
of line character. In text file some internal translation take
place when EOL character is read or written.

A text file can be of following types:

Regular text files

Delimited text files

Regular text files: These are the text files which


store text in the same form as typed. These files
have a file extension as . Txt .

Delimited text files: In these text files specific


character is stored to separate the values i.e after
each value a tab or comma is present.

Page 12 of 57
# Text files
# 21. To read a file count number of
alphabets, digits and special characters.
def test():
xf=open("notes.txt","r")
x=xf.read()
a=0
b=0
c=0
for i in x:
if i.isalpha():
a=a+1
elif i.isdigit():
b=b+1
else:
c=c+1
print("number of alphabets",a)
print("number of digit",b)
print("number of special character",c)
xf.close()
test()

Output-

Page 13 of 57
# 22. To read a file count number of words
having only three characters.
def count():
xf=open("notes.txt","r")
x=xf.readlines()
c=0
for i in x:
y=i.split()
for j in y:
if len(j)==3:
c=c+1
print("number of words with three characters",c)
xf.close()
count()

Output-

# 23.To read the file and display those


words that ends with t or s.
def display():
xf=open("notes.txt","r")
x=xf.readlines()
for i in x:
y=i.split()
for j in y:
if j.endswith('t') or j.endswith('s'):
print(j,end=' ')
xf.close()
display()

18
Page 14 of 57
Output-

# 24. To read a file and print those line


which starts with A or t.
def display():
xf=open("notes.txt","r")
x=xf.readlines()
for i in x:
if i.startswith('A') or i.startswith('t'):
print(i)
xf.close()
display()

Output-

Page 15 of 57
# Binary Files
# 25. Binary Files program for Adding,
Modification,Search,Display,Deletion.
import os
import pickle
def cls():
print("\n"*100)
def mainmenu():
while 1:
print( "welcome to FashionHUB".center(45))
print("1. item details")
print("2. exit")
ch= int(input("enter your choice(1-3) : "))
if ch==1:
item_details()
elif ch==2:
print("end of program")
break
else:
print("wrong choice")

def item_details():
while 1:
cls()
print("1. addition")
print("2. modification")
print("3. search")
print("4. deletion")
print("5. display report")
print("6. exit")
ck= int(input("enter your choice"))
if ck==1:
add()

Page 16 of 57
elif ck==2:
update()
elif ck==3:
search()
elif ck==4:
remove()
elif ck==5:
report()
elif ck==6:
return
else:
print("wrong choice")

def add():
cls()
xf=open("lakshay.dat","wb")
d={}
ab='y'
while ab=='y':
no= int(input("enter the item no. : "))
desc= input("enter item description : ")
qty=int(input("enter quantity of item :"))
rate=float(input("enter the price of item"))
amt=qty*rate
d['item no']=no
d['description']=desc
d['quantity']=qty
d['rate']=rate
d['amount']=amt
pickle.dump(d,xf)
ab=input("add more records[y/n] : ")
xf.close()

def update():
cls()
xf=open("lakshay.dat","rb+")

Page 17 of 57
d={}
K=True
n=int(input("enter the item no. to be updated"))
try:
while K:
k=xf.tell()
d=pickle.load(xf)
if n in d.values():
print(d)
print("1. update quantity of item")
print("2. update rate of item")
ab=int(input("enter your choice(1-2):"))
if ab==1:
q=int(input("enter the new quantity of item"))
d['quantity']=q
elif ab==2:
r=int(input("enter new item rate"))
d['rate']=r
else:
print("wrong choice")
xf.seek(k)
amt=d['quantity']*d['rate']
d['amount']=amt
print(d)
pickle.dump(d,xf)
K=False
except EOFError:
xf.close()

def search():
cls()
xf=open("lakshay.dat","rb")
d={}
n=int(input("enter a number"))
try:
while True:

Page 18 of 57
d=pickle.load(xf)
if n in d.values():
print(d)
except EOFError:
xf.close()

def report():
cls()
xf=open("lakshay.dat","rb")
d={}
xf.seek(0)
try:
while True:
d=pickle.load(xf)
print(d)
except EOFError:
xf.close()

def remove():
cls()
xf=open("lakshay.dat","rb")
xy=open("new.dat","wb")
d={}
n=int(input("enter a item no number"))
try:
while True:
d=pickle.load(xf)
if n not in d.values():
pickle.dump(d,xy)
except EOFError:
xf.close()
xy.close()
os.remove("lakshay.dat")
os.rename("new.dat","lakshay.dat")

mainmenu()

Page 19 of 57
Output –

Page 20 of 57
Page 21 of 57
Page 22 of 57
Page 23 of 57
Page 24 of 57
#CSV files
# 26. To create a csv file to store student
data (roll no.,name, marks) obtain data from
user and write five records on the file.
import csv
def create():
xf=open("student.csv","w")
obj= csv.writer(xf,delimiter=':')
obj.writerow(["roll no","Name","marks"])
ab='y'
while ab=='y':
r=int(input("enter roll no."))
n=input("enter name")
p=float(input("enter marks"))
obj.writerow([r,n,p])
ab= input("add more records [y/n] :")
xf.close()
create()

Output-

Page 25 of 57
# 27.To display the contents of csv file
student.csv.
import csv
def read():
xf=open("student.csv","r",newline="\r\n")
rcc=csv.reader(xf,delimiter=':')
for i in rcc:
print(i)
xf.close()
read()

Output-

Page 26 of 57
DATA STRUCTURE
# 28.Write a function lsearch() to pass a list
and a value search the value or item in the list
and display its contents.
def lsearch(l,val):
k=0
for i in l:
if i==val:
k=1
return (k)
l=eval(input("enter the list"))
n=int(input("enter the number to be searched"))
if lsearch(l,n)==1:
print("number is found")
else:
print("number is not found")

Output-

# 29.Binary search in array.


def bsearch(ar,item):
beg=0
last=len(ar)-1
while(beg<=last):
mid=(beg+last)//2
if(item==ar[mid]):
return mid
elif(item>ar[mid]):
beg=mid+1
Page 27 of 57
else:
last=mid-1
else:
return False
N=eval(input("enter desired linear-list in ascending order\n"))
Item=int(input("\nenter element to be searched for..."))
index=bsearch(N,Item)

if index:
print("\nelement found at index:",index,",position:",(index+1))
else:
print("\nsorry !! given element could not be found.\n")

Output-

# 30.Write a function to arrange the data in


ascending order.
def bsort(l):
for i in range(0,len(l)):
for j in range(0,len(l)-1-i):
if l[j]>l[j+1]:
l[j],l[j+1]=l[j+1],l[j]
print(l)
l=eval(input("enter the list"))
bsort(l)

Page 28 of 57
Output-

# 31.Write a function isort() and pass a


list arrange the data in ascending order
using insertion sort.
def isort():
for i in range(1,len(l)):
t=l[i]
j=i-1
while t<l[j] and j>-1:
l[j+1]=l[j]
j=j-1
l[j+1]=t
print(l)
l=eval(input("enter a list"))
isort()

Output-

# 32.To find sum of all columns of 2-d list


def col_tdlist():
k=[]
for i in range(len(l[0])):
k.append(0)
for i in range(len(l)):
for j in range(len(l)):
k[j]+=l[i][j]
print("sum of columns = ",k)
l=[]
Page 29 of 57
r=int(input("enter the no of rows"))
c=int(input("enter the no of coloums"))
for i in range(r):
row=[]
for j in range (c):
x=int(input("enter the no"))
row.append(x)
l.append(row)
col_tdlist()

Output-

# 33.To display those elements which are divisible by


4 or 7 in 2-d list
def tdlist(l):
for i in range(r):
for j in range(c):
if l[i][j]%4==0 or l[i][j]%7==0:
print(l[i][j])
l=[]
r=int(input("enter the no of rows"))
c=int(input("enter the no of coloums"))
for i in range(r):
row=[]
for j in range (c):
Page 30 of 57
x=int(input("enter the no"))
row.append(x)
l.append(row)
tdlist(l)

Output-

# 34. To implement a stack for these book


details(Book no., Book name) i.e now each item node
of stack contains two types of information a book no.
and its name just implement push, pop and display
operations.
stk=[]
def push(stk,value):
stk.append(value)
top=len(stk)-1

Page 31 of 57
def pop1(stk):
if stk==[]:
print("underflow")
else:
print("The deleted element",stk.pop())
def display(stk):
if stk==[]:
print("empty stack")
else:
for i in range(len(stk)-1,-1,-1):
print(stk[i])
while True:
print("1. To add a new value to stack")
print("2. To delete a value")
print("3. To display stack")
print("4. Exit")
ch=int(input("enter your choice(1-4)"))
if ch==1:
bno=input("enter book number")
bname=input("enter book name")
value=[bno,bname]
push(stk,value)
elif ch==2:
pop1(stk)
elif ch==3:
display(stk)
elif ch==4:
print("end of program")
break
else:
print("wrong choice")

Output-

Page 32 of 57
Page 33 of 57
# 35.Program to implement queue
operataions
def cls():
print("\n"*100)
def isEmpty(Qu):
if Qu==[]:
return True
else:
return False
def enqueue(Qu,item):
Qu.append(item)
if len(Qu)==1:
front=rear=0
else:
rear=len(Qu)-1
def Dequeue(Qu):
if isEmpty(Qu):
return"underflow"
else:
item=Qu.pop(0)
if len(Qu)==0:
front=rear=None
return item
def peek(Qu):
if isEmpty(Qu):
return"underflow"
else:
front=0
return Qu[front]
def display(Qu):
if isEmpty(Qu):
print("queue empty!")
elif len(Qu)==1:
print(Qu[0],"<==front,rear")
else:
front=0
Page 34 of 57
rear=len(Qu)-1
print(Qu[front],"<-front")
for a in range(1,rear):
print(Qu[rear],"<-rear")
queue=[]
front= None
while True:
cls()
print("queue operations")
print("1.enqueue")
print("2.Dequeue")
print("3.peek")
print("4.Display queue")
print("5.exit")
ch=int(input("enter your choice(1-5):"))
if ch==1:
item=int(input("enter item:"))
enqueue(queue,item)
input("press enter to continue...")
elif ch==2:
item=Dequeue(queue)
if item=="underflow":
print("underflow!Queue is empty!")
else:
print("Dequeue-ed item is",item)
input("press enter to continue....")
elif ch==3:
item=peek(queue)
if item=="underflow":
print("queue is empty!")
else:
print("front most item is",item)
input("press enter to continue....")
elif ch==4:
display(queue)
input("Press enter to continue....")

Page 35 of 57
elif ch==5:
break
else:
print("invalid choice!")
input("press enter to continue....")

Output-

Page 36 of 57
Page 37 of 57
Page 38 of 57
Page 39 of 57
Databases
A database may be defined as a collection of
interrelated data stored together to serve multiple
applications.

Rdms:
In relational data model, the data is organized into
tables (i.e., rows and columns). These are called
relations. A row in a table represents a relationship
among a set of values.

Mysql
SQL, Structured Query Language, was developed in
1970s in an IBM Laboratory. SQL, sometimes also
referred to as SEQUEL is a 4th generation non-
procedural language.

SQL, enables the following: (1) Creating/modifying a


database’s structure (ii) Changing security settings for
Page 40 of 57
system (iii) Permitting users for working on databases
or tables (iv) Querying database (v)
Inserting/Modifying/Deleting the database contents.

Data definition language (ddl): The SQL DDL


provides commands for defining relation schemas,
deleting relations, creating indexes, and modifying
relation schemas.

Some examples of such DDL statements are: CREATE


TABLE, ALTER TABLE, DROP TABLE, CREATE
INDEX, ALTER INDEX, DROP INDEX, RENAME
TABLE, TRUNCATE etc.

Data manipulation language (dml): The SQL


DML includes a query language based on both the
relational algebra and the tuple relational calculus. It
includes also commands to insert, delete, and modify
tuples in the database.

Some examples of such DML statements are: SELECT,


LOCK TABLE ect.

Transaction control language (TCL):A


transaction is successfully completed (known as
COMMIT) if and only if all its constituent steps are
successfully completed. To manage and control the
transactions, the transaction control commands are
used. These commands manage changes made by DML
commands. Some examples of TCL commands are:
Page 41 of 57
COMMIT, ROLLBACK, SAVEPOINT, SET
TRANSACTION.

SQl commands:
1.Show databases; It displays all the database, of the
system.

2.create database <Name>; It is used to create a


new database in the system.

3.Use <database name >; It is used to open a Specific


database.

4.Show tables; to display the list of table of the


database we have opened.

5.Create table; It is used to create a table With the


specified name.

6.Describe table name ; it is used to show the


structure of the specified table.

7.Select; It is used to display the records of the table.

8.Insert into; The rows are added command to


relation using insert command.

9.Delete command ; This command removes rows


from the table.

10.Update Command ; It is used to Contents modify


the of a table (increase, decrease or change).

Page 42 of 57
11. Group by; The GROUP BY clause combines all
those records that have identical values in a
particular field or a group of fields.

12. Group by – having; The HAVING clause places


conditions on groups in contrast to WHERE clause
that places conditions on individual rows.

Creating a table :--


Create database practical;

use practical;

create table employee_info(emp_id int primary key,emp_name varchar(30),DOB


date, DateOfJoin date, email_id varchar(30),address varchar(30), state
varchar(20),pincode int, phone_no varchar(15),sex varchar(10));

alter table employee_info add department varchar(20), designation varchar(20);

insert into employee_info values(101,'LAKSHAY SINGHAL','2005-02-24','2019-05-


02','KAVI NAGAR GAJRAULA','8266081865','MALE','COMPUTER SC','CEO');

insert into employee_info values(102,'ANSH YADAV','2005-05-02','2019-06-


04','TEVA COLONY GAJRAULA','8791196187','MALE','COMPUTER SC','MANAGER');

insert into employee_info values(103,'ADITYA BHATT','2005-02-25','2020-03-


22','C-44 TEVA COLONY
GAJRAULA','8979953163','MALE','MECHANICAL','MANAGER');

insert into employee_info values(104,'ANSH SHARMA','2005-05-10','2020-10-


14','TEACHERS COLONY GAJRAULA','8077869584','MALE','HR','MANAGER');

insert into employee_info values(105,'ARCHISHREE GUPTA','2005-06-21','2020-


10-14','JUBILIANT COLONY GAJRAULA','9897137127','FEMALE','HR','MANAGER');

Page 43 of 57
insert into employee_info values(106,'AYUSH VERMA','2005-05-17','2021-12-
24','MDA GAJRAULA','9913979603','MALE','MECHANICAL','CLERK');

insert into employee_info values(107,'SAMIKSHA GARG','1998-01-10','2022-04-


17','GOL ROAD DELHI','8649531854','FEMALE','COMPUTER SC','CLERK');

insert into employee_info values(108,'PIYA SHARMA','2005-10-12','2022-04-


22','SECTOR-62 NOIDA','9465865875','FEMALE','MECHANICAL','SALESMAN');

insert into employee_info values(109,'KAJOL DEVGAN','1974-08-05','2021-03-


06','CHANDNI CHOWK DELHI','8846328566','FEMALE','HR','OFFICER');

insert into employee_info values(110,'DISHA PATANI','1992-06-13','2021-07-


24','BANDRA MUMBAI','9348952675','FEMALE','COMPUTER SC','DIRECTOR');

create table salary(emp_id int,basic_salary float(10,2),HRA float(10,2),DA


float(10,2),PF float(10,2),Net_Salary float(10,2),Gross_Salary float(10,2));

insert into salary values(101,100000,00,00,00,00,00);

insert into salary values(102,80000,00,00,00,00,00);

insert into salary values(103,60000,00,00,00,00,00);

insert into salary values(104,80000,00,00,00,00,00);

insert into salary values(105,85000,00,00,00,00,00);

insert into salary values(106,35000,00,00,00,00,00);

Page 44 of 57
insert into salary values(107,45000,00,00,00,00,00);

insert into salary values(108,30000,00,00,00,00,00);

insert into salary values(109,60000,00,00,00,00,00);

insert into salary values(110,65000,00,00,00,00,00);

# 36. MYSQl questions:


1.Display all the information of the employee_info
table.

➢ select * from employee_info;

Page 45 of 57
2.Display the structure of the table employee_info.

➢ describe employee_info;

3.List the employees who are joined in the year 2020.

➢ SELECT * FROM Employee_info WHERE DateOfJoin >'2022-


01-01';

4.calculate values of HRA, DA, PF, NET SALARY


and GROSS SALARY from salary table.

➢ update salary set hra=basic_salary*10/100,


da=basic_salary*7/100, pf=basic_salary*6/100,
net_salary=basic_salary+hra+da,
gross_salary=net_salary+pf;

Page 46 of 57
5.To fetch all the Employees who are managers.

➢ select emp_name from Employee_info where designation


like 'manager';

6. To remove the employee from employee_info whose


name starts with k.

➢ delete from employee_info where name like ‘d%’;

Page 47 of 57
7.To find the maximum, minimum, and average
salary of the employees.

➢ select max(basic_salary), min(basic_salary),


avg(basic_salary) from salary;

8. To find the employee id whose salary lies in the


range of 80000 and 150000.

➢ select basic_salary from salary where basic_salary>80000


and basic_salary<150000;

9.To fetch the employees whose name begins with any


two characters, followed by a text “sh” and ends with
any sequence of characters.

➢ select emp_name from employee_info where emp_name


like '__sh%';

Page 48 of 57
10.show emp_no, emp_name and salary in ascending
order of salary.

➢ select a.emp_id,a.emp_name,b.net_salary from


employee_info a,salary b where a.emp_id=b.emp_id
order by b.net_salary;

11.show the emp_id of those whose name starts with ‘A’


or ends in ‘A’.

➢ select emp_id from employee_info where emp_name


like "a%a";

12.show the eldest date of birth and current date.

➢ select min(DOB), curdate() from employee_info;

Page 49 of 57
13.add column bonus.

➢ alter table salary add(bonus float(9));

14. select concat(emp_name,designation) from


employee_info where department like ‘computer sc';

15.To give increment to the employees as 10% of basic


salary as bonus.

➢ update salary set bonus=basic_salary*10/100;

Page 50 of 57
16.select emp_id, left(gross_salary,3) from salary;

17. display the names, net salary, gross salary of all the
male employees with their department and
designation.

➢ select a.emp_name, b.net_salary,


b.gross_salary,a.department, a.designation from
employee_info a, salary b where a.emp_id=b.emp_id
and sex like 'male';

18.Select department, count(*) from employee_info


group by department;

Page 51 of 57
19.display length of each name.

➢ select length(address),emp_id from employee_info;

20.Remove the table salary.

➢ Drop table salary;

Page 52 of 57
Interface Python
with MySQL
# 37.Create a database and table through
python mysql interface
import mysql.connector as myc

def create():

mycon=myc.connect (host="localhost", user="root", passwd="1234",


database ="employee_details")

if not mycon.is_connected():

print("not connected")

else:

cur=mycon.cursor()

cur.execute("create table emp(empid int primary key, ename


varchar(20),salary float(10,1))")

ab='y'

while ab=='y':

a=int(input("enter employee id : "))

b=input("enter name of employee : ")

c=float(input("enter employee salary : "))

cur.execute("insert into emp (empid,ename,salary)


values({},'{}',{})".format(a,b,c))

Page 53 of 57
ab=input("do you want to add more records [y/n] : ")

mycon.commit()

mycon.close()

create()

Output-

Page 54 of 57
# 38.To display first three rows fetched from
emp table of database employee
import mysql.connector as myc
def display():
mycon=myc.connect (host="localhost", user="root", passwd="1234",
database="employee_details")
if not mycon.is_connected():
print("not connected")
else:
cur=mycon.cursor()
cur.execute("select*from emp")
row=cur.fetchmany(3)
for i in row:
print(i)
mycon.close()
display()

Page 55 of 57
Output-

# 39.To update in the employee information


import mysql.connector as myc
def modify():
mycon=myc.connect (host="localhost", user="root", passwd="1234",
database="employee_details")
if not mycon.is_connected():
print("not connected")
else:
cur=mycon.cursor()
a=input("enter new name : ")
b=float(input("enter new salary : "))
c=int(input("enter the employee id you want to change : "))
cur.execute("update emp set ename ='{}',salary ={} where
empid={}".format(a,b,c))
mycon.commit()
mycon.close()
modify()

Output –

Page 56 of 57
# 40. To delete information of a employee
import mysql.connector as myc
def cut():
mycon=myc.connect (host="localhost", user="root", passwd="1234",
database="employee_details")
if not mycon.is_connected():
print("not connected")
else:
cur=mycon.cursor()
a=int(input("enter employee id"))
cur.execute("delete from emp where empid ={}".format(a))
count=cur.rowcount
mycon.commit()
print("No of rows left after deletion of a data :",count)
mycon.close()
cut()

Output –

Page 57 of 57

You might also like