0% found this document useful (0 votes)
11 views55 pages

Programming Exercises for Beginners

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)
11 views55 pages

Programming Exercises for Beginners

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

INDEX

Page Initial of
[Link] Date Exercise Name Marks
No Teacher
Program to calculate area of a
1.
triangle, circle, regular polygon.
Program to check whether a given
string is palindrome, count the
2. occurrence of a given character and
replace the character at the given
index with user given value.
Program to find the maximum,
3. minimum, sum of elements in the
list.
A menu driven program to Display
factorial of a number, Find sum of first
4. n natural numbers, Display n terms of
Fibonacci series and Sum of digits of a
number.
Program to check if a string is
5. palindrome, find length and reverse
a string.
Program to find number of vowels,
6. digits, spaces, consonants and
symbol in given text file.
Program to display number of times
each word appears in the file and to
7.
find word with maximum and
minimum length
Program to create a binary file using
8.
pickle library
Program to create a binary file using
9.
pickle library
Program To Insert Data Into CSV
10.
File
Program to perform operations on
11.
the csv file after reading it.
Program to find the occurrence of a
12.
particular word in a text file.
Program to store uppercase,
13. lowercase characters in a separate
text file.
14. Program to count number of
records present in CSV file.
Program to replace all spaces from
15.
text with special character

1
16. Implementation Of Stack
17. Display Unique Vowels In Stack
To check whether a string is a
18. Palindrome or not using Stack

19. Mysql -1
20. Mysql -2
21. Mysql Joins
22. Mysql connectivity-1
23. Mysql connectivity-2
24. Mysql connectivity-3
25. Mysql connectivity-4

2
Ex no: 1 DATE:
PROGRAM TO CALCULATE THE AREA OF A TRIANGLE, CIRCLE AND REGULAR
POLYGON
AIM:
To write a program to calculate the area of a triangle,circle and regular polygon .
PROGRAM:
print("Enter 1 for calculation of area of TRIANGLE")
print("Enter 2 for calculation of CIRCLE")
print("Enter 3 for calculation of area of REGULAR POLYGON")
ch=True
while ch:
a=int(input("Enter your choice "))
if a==1:
h=float(input("Enter height of Triangle: "))
b=float(input("Enter base of Triangle: "))
s=h*b/2
print(s,"is the area of triangle")
elif a==2:
r=float(input("Enter radius of Circle: "))
s=3.14*r**2
print(s,"is the area of circle")
elif a==3:
p=int(input("Enter perimeter: "))
a=int(input("Enter apothem: "))
s=1/2*p*a
print(s,"is the area of regular polygon")
else:
print("Invalid choice, enter right choice")
ch=eval(input("Enter True to continue/ False to exit "))

OUTPUT:
Enter 1 for calculation of area of TRIANGLE
Enter 2 for calculation of CIRCLE
Enter 3 for calculation of area of REGULAR POLYGON
Enter your choice 1
Enter height of Triangle: 30
Enter base of Triangle: 15
225.0 is the area of triangle
Enter True to continue/ False to exit True
Enter your choice 2
Enter radius of Circle: 25
1962.5 is the area of circle
Enter True to continue/ False to exit True
3
Enter your choice 3
Enter perimeter: 20
Enter apothem: 4
40.0 is the area of regular polygon
Enter True to continue/ False to exit False

RESULT:
Thus, the program to calculate the area of a triangle, circle and regular polygon is executed
successfully and the output verified.

4
EX NO: 2 DATE:

PROGRAM TO CHECK WHETHER A GIVEN STRING IS PALINDROME, COUNT


THE OCCURRENCE OF A GIVEN CHARACTER AND REPLACE THE CHARACTER
AT THE GIVEN INDEX WITH USER GIVEN VALUE.
AIM:
To write a program to checkwhether a given string is palindrome, count the occurrence of a given
character and replace the character at the given index with user given value.
PROGRAM:
def pal(s):
if s==s[::-1]:
print("String is a palindrom")
else:
print("String is not a palindrome")
def count(s):
a=input("Enter a character to be counted: ")
print(a,"appears",[Link](a),"times")
def change(s):
b=input("Enter the character to be changed: ")
c=input("Enter a new character: ")
x=[Link](b,c)
print("New string is",x)
s=input("Enter a string: ")
while True:
print("Enter 1 to check string is palindrome")
print("Enter 2 to count number of occurrences")
print("Enter 3 to replace a character")
print("Enter 4 to exit")
ch=int(input("Enter your choice: "))
if ch==1:
pal(s)
elif ch==2:
count(s)
elif ch==3:
change(s)
else:
break

OUTPUT:

Enter a string: Hello welcome back


5
Enter 1 to check string is palindrome
Enter 2 to count number of occurrences
Enter 3 to replace a character
Enter 4 to exit
Enter your choice: 1
String is not a palindrome
Enter 1 to check string is palindrome
Enter 2 to count number of occurrences
Enter 3 to replace a character
Enter 4 to exit
Enter your choice: 2
Enter a character to be counted: e
e appears 3 times
Enter 1 to check string is palindrome
Enter 2 to count number of occurrences
Enter 3 to replace a character
Enter 4 to exit
Enter your choice: 3
Enter the character to be changed: H
Enter a new character: h
New string is hello welcome back
Enter 1 to check string is palindrome
Enter 2 to count number of occurrences
Enter 3 to replace a character
Enter 4 to exit
Enter your choice: 4

RESULT:
Thus, the program to check whether a given string is palindrome, count the occurrence of a given
character and replace the character at the given index with user given value is executed and the
output is verified.

6
EX NO: 3 DATE:
PROGRAM TO FIND THE MAXIMUM, MINIMUM, SUM OF ELEMENTS IN THE LIST
AIM:
To write a program with functions to find out maximum, minimum and sum of elements of a
list.
PROGRAM:
def mi(l):
print(min(l),"is the minimum number in the list")
def ma(l):
print(max(l),"is the maximum number in the list")
def add(l):
print(sum(l),"is the sum of all elements of the list")
l=eval(input("Enter a list of numbers: "))
while True:
print("Enter 1 to print maximum number")
print("Enter 2 to print minimum number")
print("Enter 3 to add all element")
print("Enter 4 to quit")
ch=int(input("Enter your choice: "))
if ch==1:
ma(l)
elif ch==2:
mi(l)
elif ch==3:
add(l)
else:
break

OUTPUT:

Enter a list of numbers: [1,2,3,4,5,6,7,8,9,10]


Enter 1 to print maximum number
Enter 2 to print minimum number
Enter 3 to add all element
Enter 4 to quit
Enter your choice: 1
10 is the maximum number in the list
Enter 1 to print maximum number
Enter 2 to print minimum number
Enter 3 to add all element
Enter 4 to quit
Enter your choice: 2

7
1 is the minimum number in the list
Enter 1 to print maximum number
Enter 2 to print minimum number
Enter 3 to add all element
Enter 4 to quit
Enter your choice: 3
55 is the sum of all elements of the list
Enter 1 to print maximum number
Enter 2 to print minimum number
Enter 3 to add all element
Enter 4 to quit
Enter your choice: 4

RESULT:
Thus, program to find out maximum, minimum and sum of all elements is executed and the output
is verified.

8
EX NO: 4 DATE:
A MENU DRIVEN PROGRAM TO DISPLAY FACTORIAL OF A NUMBER, FIND SUM
OF FIRST N NATURAL NUMBERS,DISPLAY N TERMS OF FIBONACCI SERIES AND
SUM OF DIGITS OF A NUMBER.
AIM:
To write a menu driven program to Display factorial of a number, Find sum of first n natural
numbers,Display n terms of Fibonacci series and Sum of digits of a number.

PROGRAM:
def fact(n):
num=n
fac=1
while n>0:
fac=fac*n
n=n-1
print("Factorial of",num,"is",fac)
def sum1(n):
s=0
num=n
while n>0:
s=s+n
n=n-1
print("Sum of natural numbers till",num,"is",s)
def fib(n):
a=0
b=1
print("Fibonacci series")
print(a)
print(b)
for i in range(1,n):
c=a+b
print(c)
a=b
b=c
def sum2(n):
num=n
sum1=0
while n>0:
rem=n%10
sum1=sum1+rem
n=n//10
print("Sum of digits of",num,"is",sum1)
n=int(input("Enter a number: "))
while True:
print("Enter 1 to find factorial of a number")
print("Enter 2 to find sum of n natural numbers")
print("Enter 3 to find Fibonacci series")
print("Enter 4 to find sum of digits of a number")
9
print("Enter 5 to quit")
ch=int(input("Enter your choice: "))
if ch==1:
fact(n)
elif ch==2:
sum1(n)
elif ch==3:
fib(n)
elif ch==4:
sum2(n)
else:
break

OUTPUT:

Enter a number: 12
Enter 1 to find factorial of a number
Enter 2 to find sum of n natural numbers
Enter 3 to find Fibonacci series
Enter 4 to find sum of digits of a number
Enter 5 to quit
Enter your choice: 1
Factorial of 12 is 479001600
Enter 1 to find factorial of a number
Enter 2 to find sum of n natural numbers
Enter 3 to find Fibonacci series
Enter 4 to find sum of digits of a number
Enter 5 to quit
Enter your choice: 2
Sum of natural numbers till 12 is 78
Enter 1 to find factorial of a number
Enter 2 to find sum of n natural numbers
Enter 3 to find Fibonacci series
Enter 4 to find sum of digits of a number
Enter 5 to quit
Enter your choice: 3
Fibonacci series
0
1
1
2
3
5
8
13
21
34
55
89
144
Enter 1 to find factorial of a number
Enter 2 to find sum of n natural numbers
10
Enter 3 to find Fibonacci series
Enter 4 to find sum of digits of a number
Enter 5 to quit
Enter your choice: 4
Sum of digits of 12 is 3
Enter 1 to find factorial of a number
Enter 2 to find sum of n natural numbers
Enter 3 to find Fibonacci series
Enter 4 to find sum of digits of a number
Enter 5 to quit
Enter your choice: 5

RESULT:
Thus, the menu driven program to Display factorial of a number, Find sum of first n natural
numbers, Display n terms of Fibonacci series and Sum of digits of a number has been successfully
executed and output verified.

11
EX NO: 5 DATE:
PROGRAM TO CHECK IF A STRING IS PALINDROME, FIND LENGTH AND
REVERSE A STRING
AIM:
To write a program to check if a string is palindrome, find length and reverse a string.
PROGRAM:
def pal(s):
if s==s[::-1]:
print("String is palindrome")
else:
print("String is not palindrome")
def length(s):
print("The length of the string is",len(s))
def rev(s):
print("The reversed string is",s[::-1])
s=input("Enter a string: ")
while True:
print("Enter 1 to check if the string is palindrome")
print("Enter 2 to find the length of the string")
print("Enter 3 to reverse the string")
print("Enter 4 to exit")
ch=int(input("Enter your choice: "))
if ch==1:
pal(s)
elif ch==2:
length(s)
elif ch==3:
rev(s)
else:
break

OUTPUT:

Enter a string: Python


Enter 1 to check if the string is palindrome
Enter 2 to find the length of the string
Enter 3 to reverse the string
Enter 4 to exit
Enter your choice: 1
String is not palindrome
Enter 1 to check if the string is palindrome
Enter 2 to find the length of the string
Enter 3 to reverse the string
Enter 4 to exit
Enter your choice: 2
The length of the string is 6
Enter 1 to check if the string is palindrome
Enter 2 to find the length of the string
Enter 3 to reverse the string
12
Enter 4 to exit
Enter your choice: 3
The reversed string is nohtyP
Enter 1 to check if the string is palindrome
Enter 2 to find the length of the string
Enter 3 to reverse the string
Enter 4 to exit
Enter your choice: 4

RESULT:
Thus the program to check if a string is palindrome, find length of a string and reverse a string is
executed successfully and output is verified.

13
EX NO: 6 DATE:
A PROGRAM TO FIND NUMBER OF VOWELS, DIGITS, SPACES, CONSONANTS
AND SYMBOL IN GIVEN TEXT FILE
AIM:
To write a program to find number of vowels, digits, spaces, consonants and symbol in given
text file.
PROGRAM:
a=open("D:\PK\[Link]",'r')
s=[Link]()
vo=0
co=0
di=0
sy=0
sp=0
s=[Link]()
v='aeiou'
c='bcdfghjklmnpqrstvwxyz'
for i in s:
if i in v:
vo+=1
elif [Link]():
di+=1
elif [Link]():
sp+=1
elif i in c:
co+=1
else:
sy+=1
print("Number of vowels:",vo)
print("Number of consonants:",co)
print("Number of digits:",di)
print("Number of white spaces:",sp)
print("Number of symbols:",sy)

OUTPUT:

Number of vowels: 32
Number of consonants: 55
Number of digits: 4
Number of white spaces: 18
Number of symbols: 4

RESULT:
Thus, the program to find number of vowels, digits, consonants, spaces and symbol is executed
and output verified.

14
EX NO: 7 DATE:

A PROGRAM TO DISPLAY NUMBER OF TIMES EACH WORD APPEARS IN THE


FILE AND TO FIND WORD WITH MAXIMUM AND MINIMUM LENGTH
AIM:
To write a Program to display number of times each word appears in the file and to find word
with maximum and minimum length.
PROGRAM:
a=open("D:\PK\[Link]",'r')
s=[Link]()
x=[Link]()
l={}
for i in x:
if i not in l:
l[i]=[Link](i)
maxwd=''
ma=0
minwd=''
mi=len(x[0])
for i in x:
if ma<len(i):
maxwd=i
ma=len(i)
if mi>len(i):
minwd=i
mi=len(i)
print("The word with maximun lenght of",ma,'is',maxwd)
print("The word with minimum lenght of",mi,'is',minwd)
for i in l:
print(i,'occurs',l[i],'times')

15
EX NO: 8 DATE:

A PROGRAM TO CREATE A BINARY FILE USING PICKLE LIBRARY AND


PERFORM FILE OPERATIONS
AIM:
To write a program to create a binary file using pickle library and perform file operations
(create, append, delete, update).

PROGRAM:
import pickle
def insertrec():
empid=int(input("Enter employee id: "))
ename=input("Enter employee name: ")
sal=int(input("Enter salary"))
rec={'eid':empid,'ename':ename,'sal':sal}
f=open("D:\PK\[Link]",'ab')
[Link](rec,f)
[Link]()
def read():
f=open("D:\PK\[Link]",'rb')
while True:
try:
rec=[Link](f)
print("Employee id:",rec["eid"])
print("Employee name:",rec['ename'])
print("Employee's salary:",rec['sal'])
except EOFError:
break
[Link]()
def searchrec(r):
f=open("D:\PK\[Link]",'rb')
flag=False
while True:
try:
rec=[Link](f)
if rec['eid']==r:
print("Employee id:",rec["eid"])
print("Employee name:",rec['ename'])
print("Employee's salary:",rec['sal'])
flag=True
except EOFError:
break
if flag==False:
print("No record found")
[Link]()
def searchsal(r):
f=open("D:\PK\[Link]",'rb')
flag=False
while True:
try:
16
rec=[Link](f)
if rec['sal']>r:
print("Employee id:",rec["eid"])
print("Employee name:",rec['ename'])
print("Employee's salary:",rec['sal'])
flag=True
except EOFError:
break
if flag==False:
print("No record found")
[Link]()
while True:
print("Enter 1 to insert record")
print("Enter 2 to read record")
print("Enter 3 to search record based on employee id")
print("Enter 4 to search record based on salary")
print("Enter 5 to quit")
ch=int(input("Enter your choice: "))
if ch==1:
insertrec()
elif ch==2:
read()
elif ch==3:
r=int(input("Enter employee id: "))
searchrec(r)
elif ch==4:
r=int(input("Enter salary to search records: "))
else:
break

OUTPUT:

Enter 1 to insert record


Enter 2 to read record
Enter 3 to search record based on employee id
Enter 4 to search record based on salary
Enter 5 to quit
Enter your choice: 1
Enter employee id: 101
Enter employee name: Ram
Enter salary10000
Enter 1 to insert record
Enter 2 to read record
Enter 3 to search record based on employee id
Enter 4 to search record based on salary
Enter 5 to quit
Enter your choice: 2
Employee id: 101
Employee name: Ram
Employee's salary: 10000
Enter 1 to insert record
Enter 2 to read record
17
Enter 3 to search record based on employee id
Enter 4 to search record based on salary
Enter 5 to quit
Enter your choice: 3
Enter employee id: 102
Enter 1 to insert record
Enter 2 to read record
Enter 3 to search record based on employee id
Enter 4 to search record based on salary
Enter 5 to quit
Enter your choice: 4
Enter salary to search records: 10000
Enter 1 to insert record
Enter 2 to read record
Enter 3 to search record based on employee id
Enter 4 to search record based on salary
Enter 5 to quit
Enter your choice: 5

RESULT:
Thus, the program to create binary file using pickle library is executed successfully and output
verified.

18
EX NO: 9 DATE:

A PROGRAM TO CREATE A BINARY FILE USING PICKLE LIBRARY AND


PERFORM FILE OPERATIONS
AIM:
To write a program to create a binary file using pickle library and perform file operations
(create, append, delete, update).
PROGRAM:
import pickle
def insertrec():
sno=int(input("Enter student id: "))
sname=input("Enter student name: ")
mark=int(input("Enter mark"))
rec={'Sno':sno,'sname':sname,'mark':mark}
f=open("D:\PK\[Link]",'ab')
[Link](rec,f)
[Link]()
def read():
f=open("D:\PK\[Link]",'rb')
while True:
try:
rec=[Link](f)
print("Student roll no:",rec["Sno"])
print("Student name:",rec['sname'])
print("Student mark:",rec['mark'])
except EOFError:
break
[Link]()
def searchrec(r):
f=open("D:\PK\[Link]",'rb')
flag=False
while True:
try:
rec=[Link](f)
if rec['Sno']==r:
print("Student roll no:",rec["Sno"])
print("Student name:",rec['sname'])
print("Student mark:",rec['mark'])
flag=True
except EOFError:
break
if flag==False:
print("No record found")
[Link]()
def updaterec(r,m):
f=open("D:\PK\[Link]","rb")
reclst=[]
while True:
try:
rec=[Link](f)
19
[Link](rec)
except EOFError:
break
[Link]()
for i in range(len(reclst)):
if reclst[i]['Sno']==r:
reclst[i]['mark']=m
f=open("[Link]",'wb')
for x in reclst:
[Link](x,f)
[Link]()
def deleterec(r):
f=open("D:\PK\[Link]","rb")
reclst=[]
while True:
try:
rec=[Link](f)
[Link](rec)
except EOFError:
break
[Link]()
f=open("D:\PK\[Link]","wb")
for i in reclst:
if i['Sno']==r:
continue
[Link](i,f)
[Link]()
while True:
print("Enter 1 to insert record")
print("Enter 2 to display record")
print("Enter 3 to search record")
print("Enter 4 to update record")
print("Enter 5 to delete record")
print("Enter 6 to quit")
ch=int(input("Enter your choice:"))
if ch==1:
insertrec()
elif ch==2:
read()
elif ch==3:
r=int(input("Enter a roll no to search:"))
searchrec(r)
elif ch==4:
r=int(input("Enter a rollno:"))
m=int(input("Enter new marks:"))
updaterec(r,m)
elif ch==5:
r=int(input("Enter a rollno:"))
deleterec(r)
else:
break

20
OUTPUT:

Enter 1 to insert record


Enter 2 to display record
Enter 3 to search record
Enter 4 to update record
Enter 5 to delete record
Enter 6 to quit
Enter your choice:1
Enter student id: 234
Enter student name: Kia
Enter mark78
Enter 1 to insert record
Enter 2 to display record
Enter 3 to search record
Enter 4 to update record
Enter 5 to delete record
Enter 6 to quit
Enter your choice:2
Student roll no: 455
Student name: Ria
Student mark: 78
Student roll no: 234
Student name: Kia
Student mark: 78
Enter 1 to insert record
Enter 2 to display record
Enter 3 to search record
Enter 4 to update record
Enter 5 to delete record
Enter 6 to quit
Enter your choice:3
Enter a roll no to search:234
Student roll no: 234
Student name: Kia
Student mark: 78
Enter 1 to insert record
Enter 2 to display record
Enter 3 to search record
Enter 4 to update record
Enter 5 to delete record
Enter 6 to quit
Enter your choice:4
Enter a rollno:234
Enter new marks:80
Enter 1 to insert record
Enter 2 to display record
Enter 3 to search record
Enter 4 to update record
Enter 5 to delete record
Enter 6 to quit
Enter your choice:5
21
Enter a rollno:234
Enter 1 to insert record
Enter 2 to display record
Enter 3 to search record
Enter 4 to update record
Enter 5 to delete record
Enter 6 to quit
Enter your choice:6

RESULT:
Thus, the program to create binary file using pickle library is executed and the output is verified.

22
EX NO: 10 DATE:
PROGRAM TO INSERT DATA INTO CSV FILE

AIM:
To insert student records in CSV file.
PROGRAM:
import csv
def pro14():
f=open("D:\\[Link]","w",newline="\n")
dt=[Link](f)
print("Hai")
[Link](['Student_Id','StudentName','Score'])
[Link]()
f=open("D:\\[Link]","a",newline='\n')
while True:
st_id= int(input("Enter StudentID:"))
st_name = input("Enter Student name:")
st_score = input("Enter score:")
dt = [Link](f)
[Link]([st_id,st_name,st_score])
ch=input("Want to insert More records?(y or ‘Y’)")
ch=[Link]()
if ch !='y':
break
print("Record has been added.")
[Link]()
pro14()
OUTPUT:

RESULT:
Thus, the python program to insert student records into CSV file is executed
and output is verified.

23
EX NO: 11 DATE:
PROGRAM TO PERFORM OPERATIONS ON THE CSV FILE AFTER READING IT
AIM:
To perform following operations on the CSV file after reading it.
• Calculate total and percentage for each student.
• Display the name of student if in any subject marks are greater than 80%.
PROGRAM:
CODING:
import csv
with open('D:\\[Link]', 'w', newline='') as file:
writer = [Link](file)
[Link](["RollNo", "Name", "Mark1", "Mark2", "Mark3"])
val = int(input("Enter Student Count: "))
for i in range(0,val):
row =[]
[Link](input("Enter Student RollNo: "))
[Link](input("Enter Student Name: "))
[Link](int(input("Enter Student M1: ")) )
[Link](int(input("Enter Student M2: ") ))
[Link](int(input("Enter Student M3: ")) )
print(row)
[Link](row)
[Link]()
f = open('D:\\[Link]', 'r', newline='')
csv_f = [Link](f)
while True:
print("1) Total and Average \n2) M>80%")
val = int(input("Enter your choice:"))
if val == 1:
for row in csv_f:
print(row[1])
if (row[0] != "RollNo"):
sum = int(row[2]) + int(row[3]) + int(row[4])
print("Total is",sum)
print("Average is",sum // 3)
elif val == 2:
[Link](0)
for row in csv_f:
print(row[1])
if (row[0] != "RollNo"):
op = row[1]+" in "

24
if int(row[2]) > 80:
op += "Mark1,"
if int(row[3]) > 80:
op += "Mark2,"
if int(row[4]) > 80:
op += "Mark3,"
if op != row[1]+" in ":
op += "scored above 80%"
print(op)
else:
break
OUTPUT:
Enter Student Count: 2
Enter Student RollNo: 1
Enter Student Name: Anitha
Enter Student M1: 56
Enter Student M2: 68
Enter Student M3: 95
['1', 'Anitha', 56, 68, 95]
Enter Student RollNo: 35
Enter Student Name: Arun
Enter Student M1: 62
Enter Student M2: 95
Enter Student M3: 65
['35', 'Arun', 62, 95, 65]
1) Total and Average
2) M>80%
Enter your choioce:1
Anitha
Total is 219
Average is 73
Arun
Total is 222
Average is 74
1) Total and Average
2) M>80%
Enter your choioce:2
Anitha in Mark3 scored above 80%
Arun in Mark2 scored above 80%

RESULT:
Thus, the program to perform operations on the csv file is executed and output verified.

25
EX NO: 12 DATE:
A PROGRAM TO FIND THE OCCURRENCE OF A PARTICULAR WORD IN A TEXT
FILE
AIM:
To write a program to find the occurrence of a particular word in a text file.
PROGRAM:
text=open("D:\PK\[Link]","r")
s=[Link]()
l=[]
for i in s:
print(i,end='')
j=[Link]()
for k in j:
[Link](k)
d={}
for i in l:
d[i]=[Link](i)
val=input("\nEnter the word: ")
for i in d:
if val==i:
print(""+val+""+" counted "+str(d[i])+" times")

OUTPUT:

Twinle Twinkle Little Star


How I Wonder What You Are
Enter the word: Twinkle
Twinkle counted 1 times

RESULT:
Thus, the program to find the occurrence of a particular word in a text file is executed and the
output verified.

26
EX NO: 13 DATE:
A PROGRAM TO STORE UPPERCASE, LOWERCASE CHARACTERS IN A
SEPARATE TEXT FILE
AIM:
To write a program to store uppercase, lowercase characters in a separate text file.
PROGRAM:
f1 = open('F://[Link]', 'w')
f2 = open('F://[Link]', 'w')
f3 = open('F://[Link]', 'w')
c = True
while True:
c = input('Enter a character to write or False to terminate the program : ')
if c==False:
break
elif [Link](): # checks for lower character
[Link](c)
elif [Link](): # checks for upper character
[Link](c)
else:
[Link](c)
OUTPUT:
Enter a character to write or False to terminate the program : $$$
Enter a character to write or False to terminate the program : HAPPY
Enter a character to write or False to terminate the program : day
Enter a character to write or False to terminate the program : ###
Enter a character to write or False to terminate the program : False

RESULT:
Thus, the program to store lowercase, uppercase characters in a separate text file is written and
output is verified.

27
[Link]: 14 DATE:

PROGRAM TO COUNT NUMBER OF RECORDS PRESENT IN CSV FILE

AIM:
To write a program to Count the number of records and column names present in the
CSV file.

PROGRAM:
import csv
def pro14():
fields = [] rows
with open('[Link]', newline='') as f:
data = [Link](f)
# Following command skips the first row of CSV file
fields = next(data)
print('Field names are:')
for field in fields:
print(field, "\t") print()
print("Data of CSV File:")
for i in data:
print('\t'.join(i))
print("\nTotal no. of rows: %d"%(data.line_num))
pro14()

OUTPUT:

RESULT:
Thus, the Program to Count the number of records and column names present in the
CSV file is executed and the output is verified.

28
[Link]: 15 DATE:
PROGRAM TO REPLACE ALL SPACES FROM TEXT WITH SPECIAL CHARACTER
AIM:
To write a program to replace all spaces from Text file with special characters.

PROGRAM:

def program15():
cnt=0
with open("D:\PK\[Link]","r") as f1:
data=[Link]()
data=[Link](' ','-')
with open("D:\PK\[Link]","w") as f1:
[Link](data)
with open("D:\PK\[Link]","r") as f1:
print([Link]())
program15()

OUTPUT:

-H-e-l-l-o---t-h-i-s---i-s---t-e-x-t---f-i-l-e-

RESULT:
Thus the python program to replace all spaces from Text file with special characters is
written and the output is verified.

29
[Link]: 16 DATE:
IMPLEMENTATION OF STACK

AIM:
To write a program to perform push and pop operation on a stack using a
list.

PROGRAM:

def isEmpty(s):
if len(s)==0:
return True
else:
return False
def Push(s,item):
[Link](item)
top=len(s)-1
def Pop(s):
if isEmpty(s):
return "UNDERFLOW"
else:
val=[Link]()
if len(s)==0:
top=None
else:
top=len(s)-1
return val
def Display(s):
if isEmpty(s):
print('Stack is empty')
else:
top=len(s)-1
print(s[top],'<-top')
for i in range(top-1,-1,-1):
print(s[i])
s=[]
top=None
while True:
print("**STACK DEMONSTRATION***")
print("enter 1 to push")
print("enter 2 to pop")
print("enter 3 to display")
print("enter 4 to exit")
ch=int(input("enter your choice:"))
if ch==1:
30
val=int(input("enter the item to push:"))
Push(s,val)
elif ch==2:
val=Pop(s)
if val=="UNDERFLOW":
print("STACK IS EMPTY")
else:
print("Deleted item is:",val)
elif ch==3:
Display(s)
elif ch==4:
print("THANL YOU")
break

OUTPUT:

**STACK DEMONSTRATION***
enter 1 to push
enter 2 to pop
enter 3 to display
enter 4 to exit
enter your choice:1
enter the item to push:34
**STACK DEMONSTRATION***
enter 1 to push
enter 2 to pop
enter 3 to display
enter 4 to exit
enter your choice:1
enter the item to push:23
**STACK DEMONSTRATION***
enter 1 to push
enter 2 to pop
enter 3 to display
enter 4 to exit
enter your choice:2
Deleted item is: 23
**STACK DEMONSTRATION***
enter 1 to push
enter 2 to pop
enter 3 to display
enter 4 to exit
enter your choice:1
enter the item to push:34
**STACK DEMONSTRATION***

31
enter 1 to push
enter 2 to pop
enter 3 to display
enter 4 to exit
enter your choice:3
34 <-top
34
**STACK DEMONSTRATION***
enter 1 to push
enter 2 to pop
enter 3 to display
enter 4 to exit
enter your choice:4
THANL YOU

RESULT:
Thus, the program to perform push and pop operation on a stack using a
list is executed and the output is verified.

32
[Link]: 17 DISPLAY UNIQUE VOWELS IN STACK DATE:

AIM:
To write a program to display unique vowels present in the given word using Stack.

CODING:
vowels=['a','e','i','o','u']
word=input("Enter the word to search for vowels: ")
stack=[]
for letter in word:
if letter in vowels:
if letter not in stack:
[Link](letter)
print(stack)
print("The number of different vowels present in",word,"is",len(stack))

OUTPUT:

Enter the word to search for vowels: cluster of star


['u', 'e', 'o', 'a']
The number of different vowels present in cluster of star is 4

RESULT:
Program to display unique vowels present in the given word using Stack is executed and
the output is verified.

33
[Link]: 18 DATE:

TO CHECK WHETHER A STRING IS A PALINDROME


OR NOT USING STACK
AIM:
To write a python program to check whether a string is a palindrome or not using stack.
PROGRAM:
stack=[]
top=-1
def push(ele):
global top
top+=1
stack[top]=ele
def pop():
global top
ele=stack[top]
top-=1
return ele
def isPalindrome(string):
global stack
length=len(string)
stack=['0']*(length+1)
mid=length//2
i=0
while i<mid:
push(string[i])
i+=1
if length%2!=0:
i+=1
while i<length:
ele=pop()
if ele!=string[i]:
return False
i+=1
return True
string=input("Enter string to check: ")
if isPalindrome(string):
print("yes, the string is a palindrome")
else:
print("No, the string is not a palindrome")

34
OUTPUT:

Enter string to check: This is a stack


No, the string is not a palindrome

RESULT:
Python program to check whether a string is a palindrome or not using stack is written and
the output is verified.

35
[Link] MYSQL -1 DATE:

Write and Execute the SQL command for the following


Aim: To Understand the use of DDL and DML commands.
1. Create and open Database named MYORG
mysql> create database MYORG;
mysql> use MYORG;
Database changed

2. Create table Emp as per following Table structure.


EmpId EmpName Designation DOJ Sal Comm
Int Varchar(20) Varchar(20) Date int Int
Primary key Not null Check>1000

mysql> create table Emp (EmpIdint primary key,EmpNamevarchar(20) not null,


Designation varchar(20),DOJ date,Salint check(Sal>1000),Commint);

3. Insert 5 records with relevant information in the Emp table.

mysql> insert into Emp values(8369,'SMITH','CLERK','1990-12-18',800,null);


mysql> insert into Emp values(8499,'ANYA','SALESMAN','1991-02-20',1600,300);
mysql> insert into Emp values(8521,'SETH','SALESMAN','1991-02-22',1250,500);
mysql> insert into Emp values(8566,'MAHADEVAN','MANAGER','1991-04-
02',2985,null);
mysql> insert into Emp values(8654,'MOMIN','SALESMAN','1991-09-28',1250,400);
mysql> insert into Emp values(8698,'BINA','MANAGER','1991-05-01',2850,NULL);
mysql> insert into Emp values(8882,'SHIVANSH','MANAGER','1991-06-
09',2450,NULL);
mysql> insert into Emp values(8888,'SCOTT','ANALYST','1992-12-09',3000,NULL);
mysql> insert into Emp values(8839,'AMIR','PRESIDENT','1991-11-18',5000,NULL);
mysql> insert into Emp values(8844,'KULDEEP','SALESMAN','1991-09-08',1500,0);

mysql> SELECT * FROM EMP;


+-------+-----------+-------------+------------+------+------+
| EmpId | EmpName | Designation | DOJ | Sal | Comm |
+-------+-----------+-------------+------------+------+------+
| 8369 | SMITH | CLERK | 1990-12-18 | 800 | NULL |
36
| 8499 | ANYA | SALESMAN | 1991-02-20 | 1600 | 300 |
| 8521 | SETH | SALESMAN | 1991-02-22 | 1250 | 500 |
| 8566 | MAHADEVAN | MANAGER | 1991-04-02 | 2985 | NULL |
| 8654 | MOMIN | SALESMAN | 1991-09-28 | 1250 | 400 |
| 8698 | BINA | MANAGER | 1991-05-01 | 2850 | NULL |
| 8839 | AMIR | PRESIDENT | 1991-11-18 | 5000 | NULL |
| 8844 | KULDEEP | SALESMAN | 1991-09-08 | 1500 | 0 |
| 8882 | SHIVANSH | MANAGER | 1991-06-09 | 2450 | NULL |
| 8888 | SCOTT | ANALYST | 1992-12-09 | 3000 | NULL |
+-------+-----------+-------------+------------+------+------+
10 rows in set (0.00 sec)

4. Update all the records as add ‘Mr.’ with EmpName.


mysql> update Emp set EmpName=concat('MR.',EmpName);

5. Add one column Email of data type VARCHAR and size 30 to table Emp.
mysql> alter table Emp add Email varchar(20);

6. Drop the column Email from table Customer.


mysql> Alter table Emp drop Email;

7. Modify the column EmpName as change the size 40 characters long.


mysql> alter table Emp add Email varchar(20);
mysql>descEmp;
+-------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-------------+------+-----+---------+-------+
| EmpName | varchar(40) | YES | | NULL | |
+-------------+-------------+------+-----+---------+-------+
6 rows in set (0.03 sec)
8. Write a query to display all the records with all the columns.
mysql> select * from Emp;
+-------+--------------+-------------+------------+------+------+
| EmpId | EmpName | Designation | DOJ | Sal | Comm |
+-------+--------------+-------------+------------+------+------+
| 8369 | [Link] | CLERK | 1990-12-18 | 800 | NULL |
| 8499 | [Link] | SALESMAN | 1991-02-20 | 1600 | 300 |
| 8521 | [Link] | SALESMAN | 1991-02-22 | 1250 | 500 |
| 8566 | [Link] | MANAGER | 1991-04-02 | 2985 | NULL |
| 8654 | [Link] | SALESMAN | 1991-09-28 | 1250 | 400 |
| 8698 | [Link] | MANAGER | 1991-05-01 | 2850 | NULL |
| 8839 | [Link] | PRESIDENT | 1991-11-18 | 5000 | NULL |
| 8844 | [Link] | SALESMAN | 1991-09-08 | 1500 | 0 |
| 8882 | [Link] | MANAGER | 1991-06-09 | 2450 | NULL |
| 8888 | [Link] | ANALYST | 1992-12-09 | 3000 | NULL |
+-------+--------------+-------------+------------+------+------+
10 rows in set (0.00 sec)
9. Write a query to display EmpName and Sal of employees whose salary aregreater than or
equal to 2200
mysql> select EmpName,Sal from Emp where sal>=2200;
+------------------+---------------+
37
| EmpName | Sal |
+-----------------+----------------+
| [Link] | 2985 |
| [Link] | 2850 |
| [Link] | 5000 |
| [Link] | 2450 |
| [Link] | 3000 |
+-------------------------+---------+
10. Write a query to display details of employs who are not getting commission.
mysql> select * from Emp where Comm is NULL;
+-------+--------------+-------------+------------+------+------+
| EmpId | EmpName | Designation | DOJ | Sal | Comm |
+-------+--------------+-------------+------------+------+------+
| 8369 | [Link] | CLERK | 1990-12-18 | 800 | NULL |
| 8566 | [Link] | MANAGER | 1991-04-02 | 2985 | NULL |
| 8698 | [Link] | MANAGER | 1991-05-01 | 2850 | NULL |
| 8839 | [Link] | PRESIDENT | 1991-11-18 | 5000 | NULL |
| 8882 | [Link] | MANAGER | 1991-06-09 | 2450 | NULL |
| 8888 | [Link] | ANALYST | 1992-12-09 | 3000 | NULL |
+-------+--------------+-------------+------------+------+------+

11. Write a query to display employeename and salary of those employees who
don’t have their salary in range of 2500 to 4000.
mysql> select Empname, Sal From Emp Where Sal not between 2500 and 4000;
+-------------+------+
| empname | sal |
+-------------+------+
| [Link] | 800 |
| [Link] | 1600 |
| [Link] | 1250 |
| [Link] | 1250 |
| [Link] | 5000 |
| [Link] | 1500 |
| [Link] | 2450 |
+-------------+------+

12. Write a query to display the name of employee whose name contains “A” as
third alphabet in Ascending order of employee names.
mysql> select EmpName from Emp where EmpName like " __A%" order by Empname;

13. Write a query to display the sum of salary and commission of employees as “Total
Incentive” who are getting Commission.
mysql> select sal+comm As "Total Incentive" From Emp where comm is not NULL;
+-----------------+
| Total Incentive |
+-----------------+
| 1900 |
| 1750 |
| 1650 |
| 1500 |
+-----------------+

38
14. Write a query to display details of employs with the text “Not given”, if
commission is null.

mysql> SELECT EmpID,EmpName,Designation,DOJ,Sal,'Not Given' AS 'Comm' FROM


EMP WHERE Comm IS NULL;
+-------+--------------+-------------+------------+------+-----------+
| EmpID | EmpName | Designation | DOJ | Sal | Comm |
+-------+--------------+-------------+------------+------+-----------+
| 8369 | [Link] | CLERK | 1990-12-18 | 800 | Not Given |
| 8566 | [Link] | MANAGER | 1991-04-02 | 2985 | Not Given |
| 8698 | [Link] | MANAGER | 1991-05-01 | 2850 | Not Given |
| 8839 | [Link] | PRESIDENT | 1991-11-18 | 5000 | Not Given |
| 8882 | [Link] | MANAGER | 1991-06-09 | 2450 | Not Given |
| 8888 | [Link] | ANALYST | 1992-12-09 | 3000 | Not Given |
+-------+--------------+-------------+------------+------+-----------+
6 rows in set (0.00 sec)

15. Display the distinct job titles offered by the Organization.


mysql> select distinct designation From emp;
+-------------+
| designation |
+-------------+
| CLERK |
| SALESMAN |
| MANAGER |
| PRESIDENT |
| ANALYST |
+-------------+
5 rows in set (0.02 sec)
16. Display the Names of employees who are working as Manager or Analyst.

mysql> select EmpName from Emp where Designation='MANAGER' or


Designation='ANALYST';
+--------------+
| EmpName |
+--------------+
| [Link] |
| [Link] |
| [Link] |
| [Link] |
+--------------+
4 rows in set (0.09 sec)

17. Display the names of employees who joined on or after 01/05/1991.


mysql> select * From emp Where year(DOJ)=1991;
+-------+--------------+-------------+------------+------+------+
| EmpId | EmpName | Designation | DOJ | Sal | Comm |
+-------+--------------+-------------+------------+------+------+
| 8499 | [Link] | SALESMAN | 1991-02-20 | 1600 | 300 |
| 8521 | [Link] | SALESMAN | 1991-02-22 | 1250 | 500 |
| 8566 | [Link] | MANAGER | 1991-04-02 | 2985 | NULL |
39
| 8654 | [Link] | SALESMAN | 1991-09-28 | 1250 | 400 |
| 8698 | [Link] | MANAGER | 1991-05-01 | 2850 | NULL |
| 8839 | [Link] | PRESIDENT | 1991-11-18 | 5000 | NULL |
| 8844 | [Link] | SALESMAN | 1991-09-08 | 1500 | 0 |
| 8882 | [Link] | MANAGER | 1991-06-09 | 2450 | NULL |
+-------+--------------+-------------+------------+------+------+
8 rows in set (0.04 sec)

18. Display the employee records in order by DOJ


mysql> select * from Emp order by DOJ;
+-------+--------------+-------------+------------+------+------+
| EmpId | EmpName | Designation | DOJ | Sal | Comm |
+-------+--------------+-------------+------------+------+------+
| 8369 | [Link] | CLERK | 1990-12-18 | 800 | NULL |
| 8499 | [Link] | SALESMAN | 1991-02-20 | 1600 | 300 |
| 8521 | [Link] | SALESMAN | 1991-02-22 | 1250 | 500 |
| 8566 | [Link] | MANAGER | 1991-04-02 | 2985 | NULL |
| 8698 | [Link] | MANAGER | 1991-05-01 | 2850 | NULL |
| 8882 | [Link] | MANAGER | 1991-06-09 | 2450 | NULL |
| 8844 | [Link] | SALESMAN | 1991-09-08 | 1500 | 0 |
| 8654 | [Link] | SALESMAN | 1991-09-28 | 1250 | 400 |
| 8839 | [Link] | PRESIDENT | 1991-11-18 | 5000 | NULL |
| 8888 | [Link] | ANALYST | 1992-12-09 | 3000 | NULL |
+-------+--------------+-------------+------------+------+------+
10 rows in set (0.06 sec)

19. Display the Distinct Designation in the Organisation


mysql> select distinct designation from Emp;
+-------------+
| designation |
+-------------+
| CLERK |
| SALESMAN |
| MANAGER |
| PRESIDENT |
| ANALYST |
+-------------+
5 rows in set (0.04 sec)

RESULT:
Thus, DML and DDL commands using MySQL is executed and the output is verified.

40
[Link]: 20 MYSQL -2 DATE:

Write and Execute the SQL command for the following


Aim: To Understand the use of DDL and DML commands.
[Link] the following Table DEPT with DeptID as Primary Key.
DeptID DeptName MgrId Location
Int Varchar(20) Int Varchar(20)

mysql> create table DEPT


(DeptIdint,DeptNamevarchar(20),MgrIdint,Locationvarchar(20));
Query OK, 0 rows affected (0.09 sec)

[Link] the following record in the DEPT Table.

mysql> insert into DEPT values(10,'SALES',8566,'MUMBAI');


mysql> insert into DEPT values(20,'PERSONEL',8698,'DELHI');
mysql> insert into DEPT values(30,'ACCOUNTS',8882,'DELHI');
mysql> insert into DEPT values(40,'RESEARCH',8839,'BANGALORE');
mysql> SELECT * FROM DEPT;
+--------+----------+-------+-----------+
| DeptId | DeptName | MgrId | Location |
+--------+----------+-------+-----------+
| 10 | SALES | 8566 | MUMBAI |
| 20 | PERSONEL | 8698 | DELHI |
| 30 | ACCOUNTS | 8882 | DELHI |
| 40 | RESEARCH | 8839 | BANGALORE |
+--------+----------+-------+-----------+
4 rows in set (0.00 sec)

[Link] the table EMP as Add a column DeptID (Number)


mysql> ALTER TABLE EMP ADD DEPTID INT;

[Link] the minimum, maximum and average salary of Managers.


mysql> select min(sal), max(sal), avg(sal) From emp Where designation="Manager";
+----------+----------+-----------+
| min(sal) | max(sal) | avg(sal) |
+----------+----------+-----------+
| 2450 | 2985 | 2761.6667 |
+----------+----------+-----------+
1 row in set (0.09 sec)

[Link] the Designation wise list of employees with name, Sal and Date of Joining.
mysql> SELECT EmpName,Designation,Sal,DOJ as 'DateOfJoining'FROM EMP ORDER BY
Designation;

41
+--------------+-------------+------+---------------+
| EmpName | Designation | Sal | DateOfJoining |
+--------------+-------------+------+---------------+
| [Link] | ANALYST | 3000 | 1992-12-09 |
| [Link] | CLERK | 800 | 1990-12-18 |
| [Link] | MANAGER | 2985 | 1991-04-02 |
| [Link] | MANAGER | 2450 | 1991-06-09 |
| [Link] | MANAGER | 2850 | 1991-05-01 |
| [Link] | PRESIDENT | 5000 | 1991-11-18 |
| [Link] | SALESMAN | 1250 | 1991-02-22 |
| [Link] | SALESMAN | 1250 | 1991-09-28 |
| [Link] | SALESMAN | 1600 | 1991-02-20 |
| [Link] | SALESMAN | 1500 | 1991-09-08 |
+--------------+-------------+------+---------------+
10 rows in set (0.03 sec)

[Link] the average salary for all departments with more than 5 working people.
mysql> select avg(sal) From emp Group by deptid Having count(*)>5;
Empty set (0.06 sec)

[Link] the count of Employees grouped by DeptID.


mysql> select DeptId,count(*) from emp group by DeptId;
+--------+----------+
| DeptId | count(*) |
+--------+----------+
| 10 | 3|
| 20 | 4|
| 30 | 3|
+--------+----------+
3 rows in set (0.00 sec)

[Link] the commission as 100 who are not getting any commission.

mysql> update emp set comm=100 where comm is null;

[Link] all the records who is working as “Salesman” and salary more than 1500.
mysql> delete from emp where Designation='SALESMAN' and sal>1500;
Query OK, 1 row affected (0.02 sec)

[Link] the emp table.


mysql> drop table emp;

[Link] a command to return the position of the first occurrence of substring.


mysql> select instr('INFORMATICS','FOR');
+----------------------------+
| instr('INFORMATICS','FOR') |
+----------------------------+
| 3|
+----------------------------+
1 row in set (0.02 sec)

[Link] the command to round off value 15.93 to nearest ten’s i.e. 20.
42
mysql> SELECT ROUND(15.93,0);
+----------------+
| ROUND(15.93,0) |
+----------------+
| 16 |
+----------------+
1 row in set (0.00 sec)
13. Write the command to return the substring from the main string.

mysql> select substr('INFORMATICS',3,6);


+---------------------------+
| substr('INFORMATICS',3,6) |
+---------------------------+
| FORMAT |
+---------------------------+
1 row in set (0.00 sec)

[Link] a query to find out the result of 63.


mysql> select pow(6,3);
+----------+
| pow(6,3) |
+----------+
| 216 |
+----------+
1 row in set (0.07 sec)

[Link] command to print the day of the week of your birthday in the year 2019.
mysql> select dayname('2019-08-11');
+-----------------------+
| dayname('2019-08-11') |
+-----------------------+
| Sunday |
+-----------------------+
1 row in set (0.03 sec)

RESULT: Thus, DML and DDL commands using MySQL is executed and the output is verified.

43
Ex No: 21 Date:

MYSQL JOINS

Write and Execute the SQL command for the following


Aim: To Understand the use of joins in SQL.
[Link] the maximum salary of employees in each Department.
mysql> SELECT MAX(SAL),DESIGNATION FROM EMP GROUP BY DESIGNATION;
+----------+-------------+
| MAX(SAL) | DESIGNATION |
+----------+-------------+
| 3000 | ANALYST |
| 800 | CLERK |
| 2985 | MANAGER |
| 5000 | PRESIDENT |
| 1600 | SALESMAN |
+----------+-------------+
5 rows in set (0.04 sec)

[Link] the name of Employees along with their Designation and Department Name.
mysql> select EmpName,Designation,DeptName from Emp,Dept where
[Link]=[Link];
+--------------+-------------+----------+
| EmpName | Designation | DeptName |
+--------------+-------------+----------+
| [Link] | CLERK | SALES |
| [Link] | SALESMAN | PERSONEL |
| [Link] | SALESMAN | PERSONEL |
| [Link] | MANAGER | ACCOUNTS |
| [Link] | SALESMAN | PERSONEL |
| [Link] | MANAGER | ACCOUNTS |
| [Link] | PRESIDENT | PERSONEL |
| [Link] | SALESMAN | ACCOUNTS |
| [Link] | MANAGER | SALES |
| [Link] | ANALYST | SALES |
+--------------+-------------+----------+
10 rows in set (0.00 sec)

[Link] the number of Employees working in ACCOUNTS department.


mysql> select count(*) from emp,dept where deptname='accounts' and
[Link]=[Link];
+----------+
| count(*) |
+----------+
| 1|
+----------+
1 row in set (0.02 sec)

44
[Link] the name of Employees who is managing SALES department.
mysql> select empname From emp, dept Where deptName="SALES" and
[Link]=[Link];
+-------------+
| empname |
+-------------+
| [Link] |
| [Link] |
| [Link] |
+-------------+
3 rows in set (0.00 sec)

[Link] the name of employees who are working in Delhi .


mysql> select empname From emp, dept Where location="DELHI" and
[Link]=[Link];
+--------------+
| empname |
+--------------+
| [Link] |
| [Link] |
| [Link] |
| [Link] |
| [Link] |
| [Link] |
| [Link] |
+--------------+
7 rows in set (0.00 sec)

RESULT: Thus, SQL joins using MySQL is executed and the output is verified.

45
Ex No:22 MYSQL CONNECTIVITY-1 Date:

AIM:
To establish database connectivity for library table.
PROGRAM:
def insert1():
import [Link]
mydb=[Link](host="localhost",user="root",passwd='sns123',database='pk1')
mycon=[Link]()
n=int(input("Enter bookid: "))
name=input("Enter book name: ")
author=input("Enter author name: ")
price=int(input("Enter price: "))
cat=input("Enter catgory: ")
pub=input("Enter publisher: ")
[Link]("insert into library values('{}','{}','{}','{}','{}','{}')".
format(n,name,author,price,cat,pub))
[Link]()
print("VALUES INSERTED")
[Link]()
def update():
import [Link]
mydb=[Link](host="localhost",user="root",passwd='sns123',database='pk1')
mycon=[Link]()
p=int(input("Enter price: "))
b=input("Enter book name :")
my="update library set price={} where bname='{}'".format(p,b)
[Link](my)
print("RECORD UPDATED")
def delete():
import [Link]
mydb=[Link](host="localhost",user="root",passwd='sns123',database='pk1')
mycon=[Link]()
d=input("Enter book name to be deleted :")
st="delete from library where bname='{}'".format(d)
[Link](st)
print("BOOK DELETED")
while True:
print("Enter 1 for inserting data")
print("Enter 2 for updating data")
print("Enter 3 for deleting data")
ch=int(input("Enter your choice: "))
if ch==1:

46
insert1()
elif ch==2:
update()
elif ch==3:
delete()
else:
break

OUTPUT:
Enter 1 for inserting data
Enter 2 for updating data
Enter 3 for deleting data
Enter your choice: 1
Enter bookid: 101
Enter book name: King of Throne
Enter author name: Ana Hung
Enter price: 599
Enter catgory: Royal
Enter publisher: VK publications
VALUES INSERTED
Enter 1 for inserting data
Enter 2 for updating data
Enter 3 for deleting data
Enter your choice: 2
Enter price: 499
Enter book name :King of Throne
RECORD UPDATED
Enter 1 for inserting data
Enter 2 for updating data
Enter 3 for deleting data
Enter your choice: 3
Enter book name to be deleted :King of Thron
BOOK DELETED
Enter 1 for inserting data
Enter 2 for updating data
Enter 3 for deleting data
Enter your choice: 4

RESULT:

Thus, the database connectivity for library table is established and the output is verified.

47
Ex No:23 MYSQL CONNECTIVITY-2 Date:
AIM: To establish database connectivity for loan table and execute the queries.

CODING:
def sum1():
import [Link]
mydb=[Link](host="localhost",user="root",passwd='sns123',database='pk1')
mycon=[Link]()
a="select sum(loan_amt)from loans where interest>10"
[Link](a)
data=[Link]()
for i in data:
print(i)
def count1():
import [Link]
mydb=[Link](host="localhost",user="root",passwd='sns123',database='pk1')
mycon=[Link]()
a="select count(accno)from loans where cust_name like'%sharma'"
[Link](a)
data=[Link]()
for i in data:
print(i)
def groupby():
import [Link]
mydb=[Link](host="localhost",user="root",passwd='sns123',database='pk1')
mycon=[Link]()
a="select * from loans group by int_rate"
[Link](a)
data=[Link]()
for i in data:
print(i)
def display():
import [Link]
mydb=[Link](host="localhost",user="root",passwd='sns123',database='pk1')
mycon=[Link]()
a="select * from loans group by int_rate having instalment>'{}'".format(10)
[Link](a)
data=[Link]()
for i in data:
print(i)
while True:
print("Enter 1 to display the sum of all loan amount whose interest rate is greater than 10")
print("Enter 2 to display the count of all holders name ends with sharma")
print("Enter 3 to display interest wise details of loan account holders")
print("Enter 4 to display interest wise details of loan account holders with at least 10
installments")
ch=int(input("Enter your choice: "))
if ch==1:
sum1()
48
elif ch==2:
count1()
elif ch==3:
groupby()
elif ch==4:
display()
else:
break

OUTPUT:

Enter 1 to display the sum of all loan amount whose interest rate is greater than 10
Enter 2 to display the count of all holders name ends with sharma
Enter 3 to display interest wise details of loan account holders
Enter 4 to display interest wise details of loan account holders with at least 10 installments
Enter your choice: 1
(Decimal('2100000'),)
Enter 1 to display the sum of all loan amount whose interest rate is greater than 10
Enter 2 to display the count of all holders name ends with sharma
Enter 3 to display interest wise details of loan account holders
Enter 4 to display interest wise details of loan account holders with at least 10 installments
Enter your choice: 2
(1,)
Enter 1 to display the sum of all loan amount whose interest rate is greater than 10
Enter 2 to display the count of all holders name ends with sharma
Enter 3 to display interest wise details of loan account holders
Enter 4 to display interest wise details of loan account holders with at least 10 installments
Enter your choice: 3
(3, '[Link]', 300000, 36, None, [Link](2007, 3, 8), 2250)
(2, '[Link]', 500000, 48, Decimal('10'), [Link](2008, 3, 22), 1800)
(1, '[Link]', 300000, 36, Decimal('12'), [Link](2009, 7, 19), 1200)
(5, '[Link]', 200000, 36, Decimal('13'), [Link](2010, 1, 3), 3500)
Enter 1 to display the sum of all loan amount whose interest rate is greater than 10
Enter 2 to display the count of all holders name ends with sharma
Enter 3 to display interest wise details of loan account holders
Enter 4 to display interest wise details of loan account holders with at least 10 installments
Enter your choice: 4
(3, '[Link]', 300000, 36, None, [Link](2007, 3, 8), 2250)
(2, '[Link]', 500000, 48, Decimal('10'), [Link](2008, 3, 22), 1800)
(1, '[Link]', 300000, 36, Decimal('12'), [Link](2009, 7, 19), 1200)
(5, '[Link]', 200000, 36, Decimal('13'), [Link](2010, 1, 3), 3500)
Enter 1 to display the sum of all loan amount whose interest rate is greater than 10
Enter 2 to display the count of all holders name ends with sharma
Enter 3 to display interest wise details of loan account holders
Enter 4 to display interest wise details of loan account holders with at least 10 installments
Enter your choice: 5

RESULT:
Program to establish database connectivity for loan table is executed and the output is
verified.

49
[Link]: 24 MYSQL CONNECTIVITY-3 DATE:

AIM:
To write a program to establish database connectivity for employee table.

CODING:
COMMAND 1:
import [Link] as sqltor
mycon=[Link](host='localhost',user='root',passwd='"sns"',database='nivethitha')
cursor=[Link]()
st="select*from empl1"
[Link](st)
data=[Link]()
for row in data:
print(row)
OUTPUT 1:
(68319, 'kayling', 'president', 78122, [Link](1991, 11, 18), 6000.0, 666, 1001)
(66928, 'blaze', 'manager', 68319, [Link](1991, 5, 1), 2750.0, 444, 3001)
(67832, 'clare', 'manager', 68319, [Link](1991, 6, 9), 2550.0, 443, 1001)
(65646, 'jonas', 'manager', 68319, [Link](1991, 4, 2), 2957.0, 200, 2001)
(67858, 'scarlet', 'analyst', 65646, [Link](1991, 4, 19), 3100.0, 700, 2001)
(69062, 'frank', 'analyst', 65646, [Link](1991, 12, 3), 3100.0, 999, 2001)
COMMAND 2:
import [Link] as sqltor
mycon=[Link](host='localhost',user='root',passwd='"sns"',database='nivethitha')
cursor=[Link]()
st="select salary, name from empl1"
[Link](st)
data=[Link]()
for row in data:
print(row)
OUTPUT 2:
(6000.0, 'kayling')
(2750.0, 'blaze')
(2550.0, 'clare')
(2957.0, 'jonas')
(3100.0, 'scarlet')
(3100.0, 'frank')
COMMAND 3:
import [Link] as sqltor
mycon=[Link](host='localhost',user='root',passwd='"sns"',database='nivethitha')
cursor=[Link]()
50
st="select distinct job from empl1"
[Link](st)
data=[Link]()
print("The unique Designations of employees : ")
for row in data:
print(row)
OUTPUT 3:
The unique Designations of employees :
('president',)
('manager',)
('analyst',)
COMMAND 4:
import [Link] as sqltor
mycon=[Link](host='localhost',user='root',passwd='"sns"',database='nivethitha')
cursor=[Link]()
st="SELECT name, JOB FROM empl1"
[Link](st)
data=[Link]()
print(" EMPLOYEE & JOB")
for row in data:
print(row)
OUTPUT 4:
EMPLOYEE & JOB
('kayling', 'president')
('blaze', 'manager')
('clare', 'manager')
('jonas', 'manager')
('scarlet', 'analyst')
('frank', 'analyst')

COMMAND 5:
import [Link] as sqltor
mycon=[Link](host='localhost',user='root',passwd='"sns"',database=
'nivethitha')
cursor=[Link]()
st="select * from empl1 where job = '%s'"%('manager',)
[Link](st)
data=[Link]()
for row in data:
print(row)
OUTPUT 5:
(66928, 'blaze', 'manager', 68319, [Link](1991, 5, 1), 2750.0, 444, 3001)
(67832, 'clare', 'manager', 68319, [Link](1991, 6, 9), 2550.0, 443, 1001)
(65646, 'jonas', 'manager', 68319, [Link](1991, 4, 2), 2957.0, 200, 2001)
51
RESULT:
The program to establish database connectivity for employee table is executed and the
output is verified.

52
[Link]: 25 MYSQL CONNECTIVITY-4 DATE:

AIM:To write a program to establish database connectivity for student table.

CODING:
def menu():
c='y'
while (c=='y'):
print("1 to add record")
print("2 to update record")
print("3 to delete record")
print("4 to display record")
print("5 to exit")
ch=int(input("Enter your choice: "))
if ch==1:
adddata()
elif ch==2:
updatedata()
elif ch==3:
deldata()
elif ch==4:
fetchdata()
elif ch==5:
break
else:
print("Wrong input")
c=input("Do you want to continue or not:")
def fetchdata():
import [Link]
try:
db=[Link](host="localhost",user="root",passwd='sns123',database='pk1')
cursor=[Link]()
[Link]("SELECT * FROM student")
results=[Link]()
for i in results:
print(i)
except:
print("Error: unable to fetch data")
def adddata():
import [Link]
db=[Link](host="localhost",user="root",passwd='sns123',database='pk1')
cursor=[Link]()
[Link]("INSERT INTO student VALUES('Rithu',4000,'Science',345,'B','11')")
[Link]("INSERT INTO student VALUES('Ankush',6000,'Commce',445,'A','12')")
53
[Link]("INSERT INTO student VALUES('Pihu',3566,'Humanis',446,'A','11')")
[Link]("INSERT INTO student VALUES('Tinku',8900,'Science',545,'A+','12')")
[Link]()
print("Records added")
def updatedata():
import [Link]
try:
db=[Link](host="localhost",user="root",passwd='sns123',database='pk1')
cursor=[Link]()
sql=("Update student set sno=5000 where name='Ritu'")
[Link](sql)
print("Record updated")
[Link]()
except Exception as e:
print(e)
def deldata():
import [Link]
db=[Link](host="localhost",user="root",passwd='sns123',database='pk1')
cursor=[Link]()
sql="delete from student where name='Ritu'"
[Link](sql)
print("Record deleted")
[Link]()
menu()

OUTPUT:

1 to add record
2 to update record
3 to delete record
4 to display record
5 to exit
Enter your choice: 2
Record updated
1 to add record
2 to update record
3 to delete record
4 to display record
5 to exit
Enter your choice: 3
Record deleted
1 to add record
2 to update record
3 to delete record

54
4 to display record
5 to exit
Enter your choice: 4
('Rithu', 4000, 'Science', 345, 'B', '11')
('Ankush', 6000, 'Commce', 445, 'A', '12')
('Pihu', 3566, 'Humanis', 446, 'A', '11')
('Tinku', 8900, 'Science', 545, 'A+', '12')
1 to add record
2 to update record
3 to delete record
4 to display record
5 to exit

RESULT:
Program to establish database connectivity for Student table is executed and the output is
verified.

55

You might also like