Programming Exercises for Beginners
Programming Exercises for Beginners
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:
OUTPUT:
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:
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:
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:
15
EX NO: 8 DATE:
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:
RESULT:
Thus, the program to create binary file using pickle library is executed successfully and output
verified.
18
EX NO: 9 DATE:
20
OUTPUT:
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:
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:
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:
RESULT:
Program to display unique vowels present in the given word using Stack is executed and
the output is verified.
33
[Link]: 18 DATE:
34
OUTPUT:
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:
5. Add one column Email of data type VARCHAR and size 30 to table Emp.
mysql> alter table Emp add Email varchar(20);
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.
RESULT:
Thus, DML and DDL commands using MySQL is executed and the output is verified.
40
[Link]: 20 MYSQL -2 DATE:
[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 commission as 100 who are not getting any commission.
[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 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.
[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
[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)
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)
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:
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