You are on page 1of 59

Python Programs

Program - 1
Write a program using function(that receives n as argument) to
display the n terms of Fibonacci series.

Code:
def fibonacci(n): # n is the no of terms
p,q=0,1
if n==1:
print(p)
else:
for i in range(n//2):
print(p,q,sep=',',end=',')
p=p+q
q=p+q
if n%2!=0: # for odd value of n
print(p)
try:
n=int(input("How many terms?"))
if n<=0:
print("Please enter a +ve number")
else :
print("Fibonacci Series is :", end=" ")
fibonacci(n)
except:
print("Sorry! An error occurred")
--------------------------------------------------------
Program 1 Sample Outputs
--------------------------------------------------------

How many terms?10


Fibonacci Series is : 0,1,1,2,3,5,8,13,21,34,
---------------------------------------------------------
How many terms?1
Fibonacci Series is : 0
---------------------------------------------------------
Program - 2
Write a menu driven program to accept a line of text and perform
the following (using functions that receive the accepted text as
argument) according to the user’s choice.
1. Print the palindromic words 2. Display the longest word

Code:
def palin(text):
words=text.split()
ls=[]
for i in words:
if i==i[::-1] : # checking with reverse
ls.append(i)
if len(ls)==0:
print('No palindromic words')
else:
print('Palindromic words are:',end=' ')
for i in ls:
print(i)

def long(text):
words=text.split()
templen=len(words[0])
tempword=words[0]
for i in words:
if len(i)>=templen:
templen=len(i)
tempword=i
print('Longest Word(s) ',tempword)
print('Length is ',templen)

text=input('Enter a line of text::')


print('1. Find the palindromic Words')
print('2. Find the longest word')
ch=int(input('Enter your choice::'))
if ch==1:
palin(text)
elif ch==2:
long(text)
else:
print('Please enter 1 or 2')
--------------------------------------------------------------
Program 2 Sample Outputs
--------------------------------------------------------------
Enter a line of text::madam radar level malayalam enthusiastic

1. Find the palindromic Words


2. Find the longest word Enter your choice::2

Longest Word is enthusiastic


Length is 13
--------------------------------------------------------------

Enter a line of text::madam radarr level malayalam abcd

1. Find the palindromic Words


2. Find the longest word Enter your choice::1

Palindromic words are: madam level


malayalam
--------------------------------------------------------------
Program - 3
Define a function which takes a list as argument and copy the
prime numbers of the list into a new list and return it.

Code:
def primecheck(ls):
newlist=[]
for n in ls:
if n==1:
continue
for i in range(2,n):
if n%i==0: # finding factors
break
else:
newlist.append(n)# if prime add to list
return newlist

ls=[]
while True:
ls.append(int(input('Enter a number:')))
ch=input('Do you wish to add another no: Y/N:')
if ch in 'Nn':
break
newlist=primecheck(ls)
print('Prime numbers entered are :',newlist)
---------------------------------------------------------------
Program 3 Sample Outputs
---------------------------------------------------------------
Enter a number:5
Do you wish to add another no: Y/N:y
Enter a number:6
Do you wish to add another no: Y/N:y
Enter a number:7
Do you wish to add another no: Y/N:y
Enter a number:8
Do you wish to add another no: Y/N:y
Enter a number:9
Do you wish to add another no: Y/N:n
Prime numbers entered are : [5, 7]

---------------------------------------------------------------
Program - 4
Create a dictionary to store your friends’ names and their
birthday. Write a menu-driven program using functions which
takes the dictionary as argument and implements the following
1.Add a new friend’s data
2.Change a friend’s data
3.Delete a friend’s data
4.Display data
5.Exit

Code:
def add(d):
name=input('Enter Name:')
k=d.get(name)
if k==None:
dob=input('Enter Birthday:')
d[name]=dob
else:
print('Friends Info is already existing')

def change(d):
name=input('Enter Name:')
k=d.get(name)
if k!=None:
dob=input('Enter Birthday:')
d[name]=dob
else:
print('Friends Info is not existing')

def delete(d):
name=input('Enter Name:')
k=d.get(name)
if k:
print('Deleted item is ',name,'->',d.pop(name))
else:
print('Name does not exist')

def display(d):
for i, j in d.items():
print(i,'--->',j)
d=dict()
while True:
print('Menu\n====')
print('1.Add a new friends data ')
print('2.Change friends data')
print('3.Delete friends data')
print('4.Display data')
print('5.Exit')
ch=int(input('Enter choice:'))
if ch==1:
add(d)
elif ch==2:
change(d)
elif ch==3:
delete(d)
elif ch==4:
display(d)
elif ch==5:
break
else:
print('Enter 1,2,3 or 4')
--------------------------------------------------------------
Program 4 Sample Outputs
--------------------------------------------------------------
Menu
====
1.Add a new friends data
2.Change friends data
3.Delete friends data
4.Display data
5.Exit
Enter choice:4
Anand ---> 10-11-2007
Aparna ---> 22-11-2007
Anjali ---> 3-5-2008

Menu
====
1.Add a new friends data
2.Change friends data
3.Delete friends data
4.Display data
5.Exit
Enter choice:3
Enter Name:Arpita
Name does not exist

Menu
====
1.Add a new friends data
2.Change friends data
3.Delete friends data
4.Display data
5.Exit
Enter choice:3
Enter Name:Anjali
Deleted item is Anjali ---> 3-5-2008
-------------------------------------------------------------
Program - 5
Write a program using functions to
● Create a file named quotes.txt that stores the accepted data
from the user.
● Read the data from the text file quotes.txt line by line and
display each word separated by a #.

Code:
def createfile():#function to create a file
with open("quotes.txt","w") as f:
while True:
str=input("enter the line of text")
f.write(str+"\n")#writing data to the file
ch=input("do you want to continue, y/n:")
if ch in "nN":
break
def readdata():
with open("quotes.txt","r") as f:
y=f.readlines()#reading data as a list with each
line forming an element of the list.
for j in y:
j=j.split()
for i in j:
print(i+'#',end='')
print()
createfile() #calling the function to create a file
readdata() #calling the function to read data
--------------------------------------------------------------
Program 5 Sample Outputs
--------------------------------------------------------------
enter the line of text twinkle twinkle little star
do you want to continue, y/n:y
enter the line of texthow I wonder what you are
do you want to continue, y/n:n
twinkle#twinkle#little#star#
how#I#wonder#what#you#are#
-------------------------------------------------------------
Program – 6
Write a menu driven program to
● Create a file named Story.txt
● Append data to the file
● Read and display line by line
● Quit

Code:

def createfile():
with open("story.txt","w") as f:
while True:
str=input("enter the line of text:")
f.write(str+"\n")
ch=input("do you want to continue, y/n:")
if ch in "nN":
break
def readdata():
with open("story.txt","r") as f:
while True:
x=f.readline()#reading data line by line
if x:#if x is not empty
print(x, end="")
else:
break
def appenddata():
with open("story.txt","a") as f:
print("Enter the next line:")
while True:
x=input()
f.write(x+"\n")
ans=input("Continue?(y/n):")
if ans in 'nN':
break
try:
while True:
print("Menu")
print("1. Create file")
print("2. Read data")
print("3. Append data")
print("4. Exit")
ch=int(input("Enter your choice:"))
if ch==1:
createfile()
elif ch==2:
readdata()
elif ch==3:
appenddata()
else:
break
except:
print("Some error occurred")
--------------------------------------------------------------
Program 6 Sample Outputs
--------------------------------------------------------------
Menu
1. Create file
2. Read data
3. Append data
4. Exit
Enter your choice:1
enter the line of text:Toto Chan
do you want to continue, y/n:y
enter the line of text:The little girl at the window
do you want to continue, y/n:n
Menu
1. Create file
2. Read data
3. Append data
4. Exit
Enter your choice:3
Enter the next line
Written by
Continue?(y/n):y
Tetsuko Kuroyanagi
Continue?(y/n):n
Menu
1. Create file
2. Read data
3. Append data
4. Exit
Enter your choice:2
Toto Chan
The little girl at the window
Written by
Tetsuko Kuroyanagi
Menu
1. Create file
2. Read data
3. Append data
4. Exit
Enter your choice:4
--------------------------------------------------------------
Program – 7

Write a menu driven program to


● Create a file named prose.txt
● Display the number of vowels/ consonants/digits/special
characters in the file
● Display data line by line
● Quit

Code:

def createfile():
l=[]
with open("prose.txt",'w') as f:
while True:
x=input("Enter text")
if x:
l.append(x)
else:
break
y="\n".join(l)#converts list to a string with
print(y) #\n between each element
f.write(y) #string written to the file

def count():
with open("prose.txt",'r') as f:
dc=vc=cc=sc=0
x=f.read()
for i in x:
if i.isdigit():#counts the number of digits
dc+=1
elif i.isalpha():#checks if it an alphabet
if i in 'aeiouAEIOU':#counts the vowels
vc+=1
else: # counts the consonants
cc+=1
else:#counts the special characters
sc+=1
print("digits=",dc)
print("vowels=",vc)
print("consonants=",cc)
print("Special characters=",sc)

def displayline():#prints the data line by line


with open("prose.txt","r") as f:
x=f.readlines()
for line in x:
print(line,end="")
print()

while True:
print("Menu")
print("1. Create file prose.txt")
print("2. Count the number of vowels, consonants, Sp.char")
print("3. Read data line by line")
print("4.Exit")
ch=int(input("Enter your choice"))
if ch==1:
createfile()
elif ch==2:
count()
elif ch==3:
displayline()
else:
break
--------------------------------------------------------------
Program 7 Sample Outputs
--------------------------------------------------------------
Menu
1. Create file prose.txt
2. Count the number of vowels, consonents, Sp. char
3. Read data line by line
4.Exit
Enter your choice1
Enter textAn old silent pond
Enter textA frog jumps into the pond,
Enter textSplash! Silence again.
Enter text
An old silent pond
A frog jumps into the pond,
Splash! Silence again.
Menu
1. Create file prose.txt
2. Count the number of vowels, consonants, Sp. char
3. Read data line by line
4.Exit
Enter your choice2
digits= 0
vowels= 19
consonants= 35
Special characters= 15
Menu
1. Create file prose.txt
2. Count the number of vowels, consonants, Sp. char
3. Read data line by line
4.Exit
Enter your choice4
--------------------------------------------------------------
Program - 8
Write a menu driven program to
1. Create a file named Poem.txt
2. Copy all lines which contains the letter ‘a’ to temp.txt
3. Display the file.
4. Quit

Code:
def create():
with open("poem.txt","w") as f:
lst=[]
while True:
str=input("Enter text:")
lst.append(str)
ch=input("Do you want to continu(y/n):")
if ch in 'NOno':
break
x="\n".join(lst)
f.write(x)

def copy():
f=open("poem.txt","r")
f1=open("temp.txt","w")
x=f.readlines()
for i in x:
if 'a' in i:
f1.write(i)
f.close()
f1.close()

def disp():
f=open("poem.txt","r")
f1=open("temp.txt","r")
print("Contents of the original file")
print(f.read())
print("Contents of the new file")
print(f1.read())
f.close()
f1.close()
while True:
print("Menu")
print("1. create file poem.txt")
print("2. copy the contents to temp.txt")
print("3. display")
print("4. exit")
ch=int(input("enter your choice:"))
if ch==1:
create()
elif ch==2:
copy()
elif ch==3:
disp()
else:
break
---------------------------------------------------------------
Program 8 Sample Outputs
---------------------------------------------------------------
Menu
1. create file poem.txt
2. copy the contents to temp.txt
3. display
4. exit
enter your choice:1
Enter textthe stars shine
Do you want to continu(y/n):y
Enter text:the sun burns
Do you want to continu(y/n):y
Enter text:the moon calms
Do you want to continu(y/n):n
Menu
1. create file poem.txt
2. copy the contents to temp.txt
3. display
4. exit
enter your choice:2
Menu
1. create file poem.txt
2. copy the contents to temp.txt
3. display
4. exit
enter your choice:3
Contents of the original file
the stars shine
the sun burns
the moon calms
Contents of the new file
the stars shine
the moon calms
Menu
1. create file poem.txt
2. copy the contents to temp.txt
3. display
4. exit
enter your choice:4
--------------------------------------------------------------
Program - 9
Create a binary file to store details of n employees and display
it on the screen.
Code:
import pickle
def addemp():
with open ('employee.dat','wb') as f:
while True:
ls=[]
ls.append(int(input('Enter employee no:')))
ls.append(input('Enter employee name:'))
ls.append(float(input('Enter employee salary:')))
pickle.dump(ls,f)
ans=input('Continue(Y/n):')
if ans in 'Nn':
break

def dispemp():
with open ('employee.dat','rb') as f:
try:
while True:
j=pickle.load(f)
print('Employee No: ',j[0])
print('Employee Name: ',j[1])
print('Employee Salary: ',j[2])
except EOFError:
print('File Over')

while True:
print('1.Add Employee Info')
print('2.Display all employee info')
print('3.Exit')
ch=int(input('Enter your Choice: '))
if ch==1:
addemp()
elif ch==2:
dispemp()
elif ch==3:
break
else:
print('Sorry!! Wrong Choice')
----------------------------------------------------------------
Program 9 Sample Outputs
----------------------------------------------------------------
1.Add Employee Info
2.Display all employee info
3.Exit
Enter your Choice: 1
Enter employee no:1001
Enter employee name:John
Enter employee salary:75000
Continue(Y/n):y
Enter employee no:1002
Enter employee name:Malavika
Enter employee salary:65000
Continue(Y/n):y
Enter employee no:1003
Enter employee name:Kevin
Enter employee salary:85000
Continue(Y/n):y
1.Add Employee Info
2.Display all employee info
3.Exit
Enter your Choice:2
Employee No: 1001
Employee Name: John
Employee Salary: 75000
Employee No: 1002
Employee Name: Malavika
Employee Salary: 65000
Employee No: 1003
Employee Name: Kevin
Employee Salary: 85000
---------------------------------------------------------------
Program - 10
Create a binary file with book name and book number. Search for
a given book number and display the name of the book. If not
found, display an appropriate message.

Code:
import pickle
def addbook():
with open ('book.dat','wb') as f:
while True:
ls=[]
ls.append(int(input('Enter bookno:')))
ls.append(input('Enter bookname:'))
pickle.dump(ls,f)
ans=input('Continue(Y/n):')
if ans in 'Nn':
break

def searchbook():
b=int(input('Enter bookno to be searched:'))
flag=0
with open ('book.dat','rb') as f:
try:
while True:
j=pickle.load(f)
if j[0]==b:
print('Book Found!!!\nBook Details are\n')
print('Book No:',j[0])
print('Book Name:',j[1])
flag=1
except EOFError:
if flag==0:
print('Book Not Found!!!')

while True:
print('1.Add Book Info')
print('2.Search for a book')
print('3.Exit')
ch=int(input('Enter your Choice: '))
if ch==1:
addbook()
elif ch==2:
searchbook()
elif ch==3:
break
else:
print('Sorry!! Wrong Choice')
-------------------------------------------------------------
Program 10 Sample Outputs
-------------------------------------------------------------
1.Add Book Info
2.Search for a book
3.Exit
Enter your Choice: 1
Enter bookno:1
Enter bookname:Kite Runner
Continue(Y/n):y
Enter bookno:2
Enter bookname:Sea Of Poppies
Continue(Y/n):y
Enter bookno:3
Enter bookname:Twentieth Wife
Continue(Y/n):y
Enter bookno:4
Enter bookname:Glass House
Continue(Y/n):n
-------------------------------------------------------------
1.Add Book Info
2.Search for a book
3.Exit
Enter your Choice:2
Enter bookno to be searched:2 Book Found!!!
Book Details are
Book No: 2
Book Name: Sea Of Popies
-------------------------------------------------------------
1.Add Book Info
2.Search for a book
3.Exit
Enter your Choice2

Enter bookno to be searched:66


Book Not Found!!!
-------------------------------------------------------------
Program - 11
Create a binary file with roll number, name and marks. Input a
roll number and update the marks. Write a menu driven program
to create, display and update student records.

Code:
import pickle
import os
def addstudent():
with open ('student.dat','wb') as f:
while True:
ls=[]
ls.append(int(input('Enter rollno:')))
ls.append(input('Enter name:'))
ls.append(float(input('Enter marks:')))
pickle.dump(ls,f)
ans=input('Continue(Y/n): ')
if ans in 'Nn':
break

def updatemarks():
b=int(input('Enter rollno:'))
flag=0
f=open('student.dat','r+b')
f2=open('temp','wb')
try:
while True:
j=pickle.load(f)
if j[0]==b:
print('Student Found!!!\nDetails are:')
print('Roll No:\t',j[0])
print('Name:\t',j[1])
print('Marks:\t',j[2])
newmarks=float(input('Enter new marks:'))
j[2]=newmarks
flag=1
pickle.dump(j,f2)
print('Data Updated!')
else:
pickle.dump(j,f2)
except EOFError:
f.close()
f2.close()
os.remove('student.dat')
os.rename('temp','student.dat')
if flag==0:
print('Rollno Not Found!!!')

def display():
with open ('student.dat','rb') as f:
try:
while True:
j=pickle.load(f)
print('Roll No:\t',j[0])
print('Name:\t',j[1])
print('Marks:\t',j[2])
except EOFError:
pass

while True:
print('1.Add Student Info')
print('2.Update Marks')
print('3.Display All Info')
print('4.Exit')
ch=int(input('Enter your Choice:'))
if ch==1:
addstudent()
elif ch==2:
updatemarks()
elif ch==3:
display()
elif ch==4:
break
else:
print('Sorry!! Wrong Choice')
---------------------------------------------------------------
Program 11 Sample Outputs
---------------------------------------------------------------
1.Add Student Info
2.Update Marks
3.Display All Info
4.Exit
Enter your Choice:1
Enter rollno:1
Enter name:Merin
Enter marks:92
Enter rollno:2
Enter name:Bhavya
Enter marks:78
Enter rollno:3
Enter name:Ananya
Enter marks:75
---------------------------------------------------------------
1.Add Student Info
2.Update Marks
3.Display All Info
4.Exit
Enter your Choice:2
Enter rollno:3
Student Found!!!
Details are:
Roll No:3
Name:Ananya
Marks:75
Enter new marks:88
Data Updated!
---------------------------------------------------------------
Program 12
Write a menu driven program to
● Create a CSV file to store MobileNo, Model, Price
● Display all the Mobile Information

Code:
import csv
def create ():
with open('Mobile.csv','w',newline='') as file :
w=csv.writer(file)
while True:
n=int(input('Enter the Mobile No:'))
m=input('Enter the Model Name:')
p=int(input('Enter Price :'))
ls=[n,m,p]
w.writerow(ls)
ch=input('Wish to continue ? (Y/N):')
if ch in 'Nn':
break

def show():
with open('Mobile.csv','r') as file:
r=csv.reader(file)
for i in r:
print('Mobile No :',i[0])
print('Model :',i[1])
print('Price :', i[2])

print('Menu')
print('----')
print('1. Create a CSV file')
print('2. Display CSV file')
p=int(input('Enter choice:'))
if p==1:
create()
elif p==2:
show()
else:
print('Invalid Choice')
---------------------------------------------------------
Program 12 Sample Outputs
---------------------------------------------------------
1. Create a CSV file
2. Display CSV file
Enter choice:1
Enter the Mobile No:85475
Enter the Model Name:Aqua
Enter Price :25858
Wish to continue ? Y/N:y
Enter the Mobile No:65234
Enter the Model Name:iPhone
Enter Price :56464
Wish to continue ? Y/N:n
1. Create a CSV file
2. Display CSV file
Enter choice:2
Mobile No : 85475
Model : Aqua
Price : 25858
Mobile No : 65234
Model : iPhone
Price : 56464
---------------------------------------------------------
Program - 13
Write a menu driven program to create a CSV file to store laptop
details[ no, name, price ] and display details of laptops priced
less than 50000.
Code:
import csv
def createlaptop():
with open('laptop.csv','w',newline='') as f:
w=csv.writer(f)
while True:
ls=[]
ls.append(int(input('Enter laptop no:')))
ls.append(input('Enter brand name:'))
ls.append(float(input('Enter price:')))
w.writerow(ls)
c=input('Continue? Y/N:')
if c in 'nN':
break

def searchlaptop():
with open('laptop.csv','r') as f:
flag=0
r=csv.reader(f)
for i in r:
if float(i[2])<50000:
print('No:',i[0],'Brand',i[1])
flag=1
if flag==0:
print('All laptops are expensive!!!')

while True:
print('1.Create a CSV file with laptop info')
print('2.Search for laptop priced below 50000')
print('3.Exit')
ch=int(input('Enter choice:'))
if ch==1:
createlaptop()
elif ch==2:
searchlaptop()
elif ch==3:
break
else:
print('Invalid Choice')
---------------------------------------------------------
Program 13 Sample Outputs
---------------------------------------------------------
1.Create a CSV file with laptop info
2.Search for laptop priced below 50000
3.Exit
Enter choice:1 Enter laptop no:1
Enter brand name:Apple
Enter price:67000
Continue? Y/N:y
Enter laptop no:2
Enter brand name:HP
Enter price:49000 Continue? Y/N:Y
Enter laptop no:3
Enter brand name:Acer
Enter price:38000 Continue? Y/N:y
---------------------------------------------------------
1.Create a CSV file with laptop info
2.Search for laptop priced below 50000
3.Exit
Enter choice:2
No: 2 Brand HP
No: 3 Brand Acer
---------------------------------------------------------
Program - 14
Write a random number generator that generates random numbers
between 1 and 6 (simulates a game to guess the number using a
dice).
Code:
import random
import time
while True:
print('Guess the no on the dice')
no=int(input('Enter a number between 1 and 6:'))
if no <1 or no>6:
print('Invalid Number')
continue
else:
rndno=random.randint(1,6)
print('Checking...')
time.sleep(3)
if rndno==no:
print('You guessed it right!!!')
else:
print('Unsuccessful Guess, Try Again!!!')
ch=input('Try Once Again? Y/N:')
if ch in ['N','n','NO','no','No']:
break
---------------------------------------------------------
Program 14 - Sample Outputs
---------------------------------------------------------
Guess the no on the dice
Enter a number between 1 and 6:1
Checking...
Unsuccessful Guess, Try Again!!!
Try Once Again? Y/N:y
---------------------------------------------------------
Guess the no on the dice
Enter a number between 1 and 6:2
Checking...
You guessed it right!!! Try Once Again? Y/N:y
---------------------------------------------------------
Program – 15
A list contains following details of a customer: [Customer_name,
Phone_number, City]
Write the following user defined functions to perform given
operations on the stack named status:
(i) Push_element()-To Push an object containing name and Phone
number of customers who live in Goa to the stack
(ii)Pop_element() -To Pop the objects from the stack and display
them. Also, display “Stack Empty” when there are no elements in
the stack.
(iii) disp_stack()- To display the elements of the stack.

Code:
status=[]

def push_element(cust): #to push an element to the stack


if cust[2]=="Goa":
L1=[cust[0],cust[1]]
status.append(L1)

def pop_element():#to delete an element from the stack


if len(status)!=0:
dele=status.pop()
print('The deleted element is',dele)
else:
print("Stack Empty")

def disp_stack():#to display the elements in the stack


for i in range(len(status)-1,-1,-1):
print(status[i])

while True:
print("1. Push element")
print("2. Pop element")
print("3. Display stack")
print("4. Exit")
ch=int(input("Enter choice:"))
if ch==1:
cust_name=input("Ënter the customer name:")
phno=input("Enter phone number:")
city=input("Enter city:")
cust=[cust_name,phno,city]
push_element(cust)
elif ch==2:
pop_element()
elif ch==3:
disp_stack()
else:
break
-----------------------------------------------------------------
Program 15 Sample output
-----------------------------------------------------------------
1. Push element
2. Pop element
3. Display stack
Enter choice:1
Ënter the customer name:Rahul
Enter phone number:9988776600
Enter city:Goa
1. Push element
2. Pop element
3. Display stack
Enter choice:1
Ënter the customer name:Hari
Enter phone number:1122334455
Enter city:Kochi
1. Push element
2. Pop element
3. Display stack
Enter choice:3
['Rahul', '9988776600']
1. Push element
2. Pop element
3. Display stack
Enter choice:2
['Rahul', '9988776600']
Stack Empty
1. Push element
2. Pop element
3. Display stack
Enter choice:4

-----------------------------------------------------------------
Program – 16
Write a MySQL connectivity program to display the list of tables
under the database school.
import mysql.connector as sql
try:
con=sql.connect(host='localhost',user="root",passwd="bav")
cur=con.cursor()
cur.execute('show databases;')
myrec=cur.fetchall()
x=0
print("List of tables under the database school")
for i in myrec:
if 'school' in i:
x=1
cur.execute("use school")
cur.execute("show tables")
rec=cur.fetchall()
for j in rec:
print(j)
if x==0:
print("Database not present")
cur.close()
con.close()
except:
print('Could not connect to the server...')
-----------------------------------------------------------------
Program 16 Sample Outputs
-----------------------------------------------------------------
List of tables under the database school
('student',)
('teacher',)
('parent',)
-----------------------------------------------------------------
Program – 17
Write a MySQL connectivity program to add, remove and display the
records from the table student under the database project.

Code:

import mysql.connector as sql


try:
con=
sql.connect(host="localhost",user="root",passwd="bav",database
="project")
mycursor=con.cursor()
except:
print('Could not establish connection...')
con.close()

def add_rec():
admno=int(input("enter the admission number"))
name=input("enter name")
std=input("enter the class")
marks=float(input("enter the marks"))
str="insert into student values({},'{}','{}',{})".format
(admno,name,std,marks)
mycursor.execute(str)
con.commit()
print("The record is inserted")

def disp_rec():
print("Records from the table student-")
str1="select * from student"
mycursor.execute(str1)
myrec=mycursor.fetchall()
for i in myrec:
print(i)

def remove_rec():
admno=input("enter the admission number")
str1="delete from student where admno="+admno
mycursor.execute(str1)
con.commit()
print("The record is removed")

while True:
print("1. add record\n2. display record \n3. delete record")
ch=int(input("Ënter your choice?"))
if ch==1:
add_rec()
elif ch==2:
disp_rec()
elif ch==3:
remove_rec()
else:
break
-----------------------------------------------------------------
Program 17 Sample Outputs
-----------------------------------------------------------------
1. add record
2. display record
3. delete record
Ënter your choice?1
enter the admission number1010
enter nameJubin
enter the classXII
enter the marks90
The record is inserted
1. add record
2. display record
3. delete record
Enter your choice?3
enter the admission number1008
The record is removed
1. add record
2. display record
3. delete record
Enter your choice?2
Records from the table student-
(100, 'Eapen', 'X', Decimal('67.00'))
(1001, 'Anu', 'XI', Decimal('87.00'))
(1003, 'David', 'XII', Decimal('70.00'))
(1004, 'Shershah', '10', Decimal('89.00'))
(1010, 'Jubin', 'XII', Decimal('90.00'))
1. add record
2. display record
3. delete record
Enter your choice?4
-----------------------------------------------------------------
Program – 18
Write a MySQL connectivity program to increase the marks of
students, with marks greater than an accepted mark, by 10. Also
display the updated records. (From the table student under the
database project).

Code:
import mysql.connector as con
try:
mydb=
con.connect(host="localhost",user="root",passwd="bav",database
="project")
mycursor=mydb.cursor()
except:
print('Could not establish connection')
mycursor.close()
mydb.close()

def disp_rec():
str2="Select * from student"
mycursor.execute(str2)
myrec=mycursor.fetchall()
print("Records from the table student before updating-")
for i in myrec:
print(i)
marks=input("Enter the mark")
str1="update student set marks=marks+10 where marks>="+
str(marks)
mycursor.execute(str1)
mydb.commit()
str2="Select * from student"
mycursor.execute(str2)
myrec=mycursor.fetchall()
print("Records from the table student after updating-")
for i in myrec:
print(i)

disp_rec()
-----------------------------------------------------------
Program 18 Sample Outputs
-----------------------------------------------------------
Records from the table student before updating-
(100, 'Eapen', 'X', Decimal('67.00'))
(1001, 'Anu', 'XI', Decimal('87.00'))
(1003, 'David', 'XII', Decimal('70.00'))
(1004, 'Shershah', '10', Decimal('89.00'))
(1010, 'Jubin', 'XII', Decimal('90.00'))

Enter the mark75


Records from the table student after updating-
(100, 'Eapen', 'X', Decimal('67.00'))
(1001, 'Anu', 'XI', Decimal('97.00'))
(1003, 'David', 'XII', Decimal('70.00'))
(1004, 'Shershah', '10', Decimal('99.00'))
(1010, 'Jubin', 'XII', Decimal('100.00'))
-----------------------------------------------------------
MySQL
EXERCISES
MySQL 1 - EMP TABLE

Write SQL queries based on the table emp.

1. To display the name and job of employees in the alphabetic


order emp name.

2. To display the empno and ename of employees belonging to


department 10 or 20.

3. To display the job of the employee named Scott.


4. To display the name and salary of Managers having salary
above 100000.

5. To display employee name, salary and job of the employees in


the decreasing order (descending) of their salaries.

6. To display the details of all executives in the table whose


name starts with 'S'
7. To add a new column called commission with datatype float
(6,2)

8. To update/modify the column named commission by giving a


commission of Rs. 500 to all Executives in table emp.

9. To display emp name, job and dept no of employees having no


commission.
10. To display the dept no and total no of employees in each
department.

Write the output of the following queries:

11. select distinct job from emp;

12. select min(salary) “Minimum salary”,max(salary) “ Maximum


salary” from emp;

13. select sum(salary),avg(salary) from emp where salary


between 10000 and 100000;
MySQL 2 - DEPT TABLE

Write SQL Queries based on Emp and Dept table.


1. Create a table name dept with columns deptno, dname and
location. Set deptno as the primary key of the table. Also
populate the table with values.

Ans: create table dept (deptno int primary key,dname varchar(20),


location varchar(20));

insert into dept values(10,’Sales’,’CHN’),(20,’Accounts’,’MUM’),


(30,’Projects’,’CHN’),(40,’Research’,’CHN’);

2. To display the details of departments 10 and 30.


3. To display the emp names and the names of their departments
from emp and dept table.

4. To display the name and location of all Executives.

5. To display the details of employees in Projects department.


Write the output of the following queries.

6. Select count(*) from dept where location=’CHN’;

7. Select distinct location from dept;

8. Select ename,emp.deptno,location from emp, dept where


emp.deptno=dept.deptno and dname like ’%j%’;
MySQL 3 - STUDENT AND EXAM TABLE
Write SQL queries based on Student and Exam table.
Table: Student

Table: Exam

1. To display the id and name of students in class XII having


marks above 60.

2. To display the names of students in the order of date of


join(doj).
3. To count the total no of cyclic tests conducted.

4. To display the name, class and marks of the students out of


50, assuming the marks obtained are out of 100.

5. To find the class and no of students belonging to each


class.

6. To find the sum and average of the marks of the students


belonging to each class if there are more than 2 students in
each class.
7. To display the name of the students, marks obtained and the
exam code of the exam held on 18th June 2021.

8. To set the exam date of examination with code=11 to


2021-08-05’;

9. To display student name, marks obtained by the students and


their class along with exam date.
10. To delete the details of examinations if max marks are not
assigned.

11. To display the name and marks of class XI students in the


descending order of their marks.

12. To update the values in max marks column of exam table by


100.
13. To remove the column maxmarks from exam table.

Write the output of the following queries.


14. Select distinct ename from exam;

15. Select studentid, name from student where name like ‘_m%’;

16. select studentid,name,ename from student cross join exam


where exam=’Midterm’;

You might also like