Download as pdf or txt
Download as pdf or txt
You are on page 1of 58

1.

FACTORIAL OF A GIVEN NUMBER

Write a program in Python to find factorial for the given number

AIM:
To find the factorial value for the given number

ALGORITHM:

Step 1: Start the program execution


Step 2: Read the value of number
Step 3: Call the function factorial(number)
Step 4: Initialize fact=1
Step 5: Check for loop , if the condition is true go to step 6 else go to step 7Step
6: Calculate fact =fact*i
Step 7: Return fact to resultStep 8: Print result
Step 9: Stop the program execution
PROGRAM:

def factorial(num):
fact=1
for i in range(1, num+1):
fact=fact*i
return fact
n=int(input("Please enter any number to find factorial: "))
result=factorial(n)
print("The factorial of", number ,"is:", result)

RESULT:
The given program is executed successfully and the result is verified.

1
OUTPUT:
Please enter any number to find factorial: 5

The factorial of 5 is: 120

2
2. FIBONACCI SERIES

Write a program in Python to find Fibonacci series for given number

AIM:

To find Fibonacci series of given number

ALGORITHM:

Step 1: Start the program execution


Step 2: Read the value of n
Step 3: Initialize a=0, b=1 , sum=0 and count=1
Step 4: Check if count<=n ,if the condition is true go to step 7 else goto step 7
Step 5: Print sum
Step 6: Increment count by 1 and assign a=b, b=sum and sum=a+b
Step 7: stop the program execution
PROGRAM:
n = int(input("Enter the value of n: "))
a=0
b=1
sum = 0
count = 1
print("Fibonacci Series: ", end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a=b
b = sum
sum = a + b

RESULT:

The given program is executed successfully and the result is verified.

3
OUTPUT:

Enter the value

of n : 5

Fibonacci

Series :

4
3. STRING PALINDROME

Write a program in Python to find given string is palindrome or

notAIM:

To check whether the given string is palindrome or not.

ALGORITHM:

Step 1: Start the program executionStep 2: Read the value


of sStep 3: Call the function isPalindrome(s)
Step 4: Check for loop, if the condition is true go to step 5 else go to
step 7 Step 5: Check if str[i]!=str[len(str)-i-1] , if the condition is true
go to step 7 elsego to step 5
Step 6: Return False to ans , then go
to step 8Step 7: Return True to ans ,
then go to step 8
Step 8: Check if(ans) , if the condition is true go to step 9 else go to
step 10Step 9: Print “The given string is Palindrome”
Step 10: Print “The given string is not a
Palindrome”Step 11: Stop the program
execution

5
PROGRAM:
def isPalindrome(str):
for i in range(0,
int(len(str)/2)):if
str[i]!=str[len(str)
-i-1]:
return False
else:
return Trues=input("Enter string:")
ans = isPalindrome(s)
if (ans):
print("The given string is Palindrome")
else:
print("The given string is not a Palindrome")

RESULT:
The given program is executed successfully, and the result is verified.

6
OUTPUT:

Enter string: madam

The given string is PalindromeEnter string:

computerThe given string is not a Palindrome

7
4. CREATING A MENU DRIVEN PROGRAM TO FIND AREA OF CIRCLE,
RECTANGLEAND TRIANGLE

AIM:
To write a menu driven Python Program to find Area of Circle, Rectangle and
Triangle.using function.

ALGORITHM:

Step 1: Start the program execution


Step 2: Read the choice value
Step 3: If ch==1 , call the function Circle(a) then print area of the circle. Else
goto Step 4
Step 4: If ch==2 ,call the function Rectangle(L,B) then print area of the
rectangle .Else goto Step 5
Step 5: If ch==3 , call the function Triangle(B,H) then print area of Triangle .
Else goto Step 6
Step 6: Print “Invalid option”
Step 7: Stop the program execution.

PROGRAM:
def Circle(r):
Area=3.141*(r**2)
print("The Area of circle is:",Area)
def Rectangle(L,B):
R=L*B
print("The Area of rectangle is:",R)
def Triangle(B,H):
R=0.5*B*H
print("The Area of triangle is:",R)
8
print("1.Area of Circle")
print("2.Area of Rectangle")
print("3.Area of Triangle")
ch=int(input("Enter your choice"))if
ch==1:
a=float(input("enter the radius value"))
Circle(a)
elif ch==2:
L=int(input("Enter the Length of the Rectangle")) B=int(input("Enter the
Breadth of the Rectangle"))Rectangle(L,B)
elif ch==3:
B=int(input("Enter the Base of Triangle:"))
H=int(input("Enter the Height of Triangle:"))
Triangle(B,H)
else:
print("Invalid option")

RESULT:
The given program is executed successfully and the result is verified.
9
OUTPUT:

1. Area of Circle
2. Area of Rectangle
3. Area of Triangle
Enter your choice:1
Enter the radius value 5
The Area of circle is: 78.525
1.Area of Circle
2. Area of Rectangle
3. Area of Triangle
Enter your choice 2
Enter the Length of the Rectangle 7
Enter the Breadth of the Rectangle 5
The Area of rectangle is: 35

10
5.MENU DRIVEN PROGROM TO PERFOR M ARITHMETIC OPERATORS

To write a python program to create a menu driven program to perform arithmetic


operations.
AIM:
To write a menu driven Python Program to perform Arithmetic operations (+,-*,
/) based on the user‟s choice.

ALGORITHM:
Step 1 : Start the execution of the program
Step 2 : Input to the variable opt , a and b
tep 3 : If choice=1, calculate c=a+b , otherwise goto step 4
Step 4 : If choice=2, calculate c=a-b , otherwise goto step 5
Step 5 : If choice=3, calculate c=a*b , otherwise goto step 6
Step 6 : If choice=4, calculate c=a/6 , otherwise goto step 7
Step 7 : print “Invalid option” Step 8: Stop the execution of the program
Program:

def sum(a,b):
c=a+b
return c
def subt(a,b):
c=a-b
return c
def mult(a,b):
c=a*b
return c
def divi(a,b):
c=a/b
return c
print("******************")
print("ARITHMETIC OPERATIONS")

11
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
while True:
opt=int(input ("Enter your choice"))
if opt==1:
a=int(input("Enter the first number"))
b=int(input ("Enter the second number"))
res=sum(a,b)
print("The sum is ",res)
elif opt==2:
a=int(input("Enter the first number"))
b=int(input ("Enter the second number"))
res=subt(a,b)
print("The difference is ",res)
elif opt==3:
a=int(input("Enter the first number"))
b=int(input ("Enter the second number"))
res=mult(a,b)
print("The product is ",res)
elif opt==4:
a=int(input("Enter the first number"))
b=int(input ("Enter the second number"))
res=divi(a,b)
print("The remainder is ",res)
else:
print("Please enter your correct choice")
break

RESULT:
The given program is executed successfully and the result is verified.

12
OUTPUT:
******************
ARITHMETIC OPERATIONS
1. Addition
2. Subtraction
3. Multiplication
4. Division
Enter your choice1
Enter the first number23
Enter the second number34
The sum is 57
Enter your choice2
Enter the first number34
Enter the second number23
The difference is 11
Enter your choice3
Enter the first number5
Enter the second number4
The product is 20
Enter your choice4
Enter the first number32
Enter the second number8
The remainder is 4.0
Enter your choice5
Please enter your correct choice:

13
6. RANDOM NUMBER GENERATION

Write a Python program for random number generation that generates random
numbers between 1 to 6 (simulates a dice).

Aim:
To write a Python program for random number generation that generates random
numbers between 1 to 6 (simulates a dice).

Algorithm:
Step 1: Start
Step 2: Import random module
Step 3: Under while loop write a random number generate that will generate
number from 1 to 6 using randint() method.
Step 4: Print the random generate number
Step 5: Stop

Program
import random
n = random.randrange(1,10)
guess = int(input("Enter any number: "))
while n!= guess:
if guess < n:
print("Too low")
guess = int(input("Enter number again: "))elif
guess > n:
print("Too high!")
guess = int(input("Enter number again: "))
else:
break
print("you guessed it right!!")

RESULT:
The given program is executed successfully and the result is verified.

14
Output:
Enter any number: 2
Too low
Enter number again: 4
Too high!
Enter number again: 3
you guessed it right!!

15
9. READ A FILE LINE BY LINE

Write a program in Python to read a text file myfile.txt line by line and display each
word separated by a #. If myfile.txt contains

For every action there is equal and opposite reaction.

Energy can neither be created nor be destroyed.

AIM:
To read a text file myfile.txt line by line and display each word separated by a #.

ALGORITHM:

Step 1: Start the program execution


Step 2: Open myfile.txt in read mode
Step 3: Check for loop, if the condition is true go to step 4 else go to step 7
Step 4: Split words in line using split( ) function
Step 5: Check for loop, if the condition is true go to step 5 else go to step 3
Step 6: print the value of i and add „#‟ symbol
Step 7: Stop the program execution

PROGRAM:

file1=open('myfile2.txt','r')
for line in file1:
word=line.split()
for i in word:
print(i,end='#')
file1.close()

RESULT:
The given program is executed successfully and the result is verified.

16
OUTPUT:

For#every#action#there#is#equal#and#opposite#reaction.#Energy#can#neither#be#creat
ed#no r#be#destroyed.#

17
10. COPYING LINES IN A FILE
Copy all the lines that contain the character `a' in a file and write it to another
file.
AIM:
To Copy all the lines that contain the character `a' in a file and write it to
another file
ALGORITHM:
Step 1: Start the program execution
Step 2: Open the file “xiics2.txt” in read mode and “xiics.txt” in write mode
Step 3: Check for line in fin , if the condition is true go to step 4 else go to step
9
Step 4: Split words in line using split( ) function
Step 5: Check for i in word , if the condition is true go to step 6 else go to step 3
Step 6: Check for letter in i , if the condition is true go to step 7 else go to step 5
Step 7: Check if letter==‟a‟ or letter= =‟A‟, if the condition is true go step 7 else
go to step 3
Step 8: Write line in text file xiics4.txt
Step 9: Close the files and stop the execution of the program

PROGRAM:
fin=open("xiics2.txt","r")
fout=open("xiics4.txt","w")
for line in fin:
word=line.split( )
for i in word:
for letter in i:
if letter=='a' or letter=='A':
fout.write(line)
fin.close( )
fout.close( )

RESULT:
The given program is executed successfully and the result is verified.

18
OUTPUT:

Xiics2.txt
We are aware if ATM cards that are used in ATM machines.
iics4.txt
Betty bought some butter. To make bitter butter better.

19
11. Write a Python program to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file

Aim:
To write Python program to read a text file and display the number of vowels/
consonants/ uppercase/ lowercase characters in the file.

Algorithm:

Step 1: Start
Step 2: Open text file in read mode using open() method
Step 3: Read the content of the file using read() method
Step 4:Write the logic for counting the Vowels,Consonants,Upper case
letters,Lower case letters using islower(),isupper(),ch in [„a‟,‟e‟,‟i‟,‟o‟,‟u‟],
ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']
Step 5: Close the file using close() method
Step 6: Print the Counting data.
Step 7: Stop

Program:

file=open("AI.TXT","r")
content=file.read()
vowels=0
consonants=0
lower_case_letters=0
upper_case_letters=0
for ch in content:
if(ch.islower()):
lower_case_letters+=1
elif(ch.isupper()):
upper_case_letters+=1
ch=ch.lower()
if (ch in ['a','e','i','o','u']):
vowels+=1

20
elif(ch in ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z']):
consonants+=1
file.close()
print("Vowels are :",vowels)
print("Consonants :",consonants)
print("Lower_case_letters :",lower_case_letters)
print("Upper_case_letters :",upper_case_letters)

AI.txt
As computer can understand only machine language, a Translator is needed to
convert a program written in assembly or hign=level language to machine
Languang to Machine Language

RESULT:
The given program is executed successfully and the result is verified.
21
Output:
('Vowels are :', 58)
('Consonants :', 90)
('Lower_case_letters :', 143)
('Upper_case_letters :', 5)

22
12. CREATE AND SEARCHING RECORDS IN A BINARY FILE

Create a binary file with name and roll number, marks. Search for a given
roll number and display the details of student, if not found display appropriate
message.

AIM:
To search a record in a binary file

ALGORITHM:
Step 1: Start the program execution
Step 2: Import the pickle module and open the file “stud.dat” in read mode
Step 3: Using load function read the student details from binary file
Step 4: Check if stud[“Rollno”]= =1003 , if the condition is true go to step 5
else go to step 6
Step 5: Print stud and set found=True
Step 6: Check if found==False then go to step 7 else go to step 8Step 7: Print
“Record found”
Step 8: Print “Record not found”
Step 9: Stop the program execution

PROGRAM:
WRITING RECORD ON BINARY FILE
import pickle
stud={}
stufile=open("stud.dat","wb")
ans='y'
while ans= ='y':
rno=int(input("Enter roll number:"))
name=input("Enter name:") mark1=int(input("Enter English mark:"))
mark2=int(input("Enter Maths mark:")) mark3=int(input("Enter CS mark:"))

23
stud["Rollno"]=rno

stud["Name"]=name
stud["Mark1"]=mark1
stud["Mark2"]=mark2
stud["Mark3"]=mark3
pickle.dump(stud,stufile)
ans=input("Do u want to append more records?(y/n)...?")
stufile.close()

SEARCHING RECORD IN A BINARY FILE


import pickle
stufile=open("stud.dat","rb")
stud={}
found=False
print("Students Details")
try:
while True:
stud=pickle.load(stufile)
if stud["Rollno"]= =1003:
print(stud)
found=True
except:
if found= =False:
print("Record not found")
else:
print("Record found")stufile.close()

24
Students Details
{'Rollno': 1001, 'Name': 'Lakshmi', 'Mark1': 88, 'Mark2': 76, 'Mark3': 93}
{'Rollno': 1002, 'Name': 'Rani', 'Mark1': 90, 'Mark2': 85, 'Mark3': 86}
{'Rollno': 1003, 'Name': 'Vishnu', 'Mark1': 67, 'Mark2': 78, 'Mark3': 89}
{'Rollno': 1004, 'Name': 'Rishi', 'Mark1': 92, 'Mark2': 67, 'Mark3': 84}
{'Rollno': 1005, 'Name': 'Seetha', 'Mark1': 86, 'Mark2': 59, 'Mark3': 70}

Students Details
{'Rollno': 1003, 'Name': 'Vishnu', 'Mark1': 67, 'Mark2': 78, 'Mark3': 89}
Record found

RESULT:
The given program is executed successfully and the result is verified.

25
OUTPUT:
Enter roll number:1001
Enter name:Lakshmi
Enter English mark:88
Enter Maths mark:76
Enter CS mark:93
Do u want to append more records?(y/n)...?y
Enter roll number:1002
Enter name:Rani
Enter English mark:90
Enter Maths mark:85
Enter CS mark:86
Do u want to append more records?(y/n)...?y
Enter roll number:1003
Enter name:Vishnu
Enter English mark:67
Enter Maths mark:78
Enter CS mark:89
Do u want to append more records?(y/n)...?y
Enter roll number:1004
Enter name:Rishi
Enter English mark:92
Enter Maths mark:67
Enter CS mark:84
Do u want to append more records?(y/n)...?y
Enter roll number:1005
Enter name:Seetha Enter English mark:86
Enter Maths mark:59
Enter CS mark:70
Do u want to append more records?(y/n)...?n

26
13. CREATING AND UPDATING RECORDS IN A BINARY FILE

Write a Python program to create a binary file with roll number, name and
marks. Input a roll number and update the marks.

AIM:
To update a record in a binary file

ALGORITHM:

Step 1: Start the program execution


Step 2: Import the pickle module and open the file “xiics1.dat” in read mode
Step 3: Read the student details using load function
Step 4: Check if stud[“Rollno”] = =rno1, if the condition is true go to step 5 else
go to step 7
Step 5: Update stud[“Mark1”]+=5 and set the file pointer to write updated
record on binary File
Step 6: Print stud and set found=True
Step 7: Check if found==False then go to step 9 else go to step 10
Step 8: Print “Record not found”
Step 9: Print “Record updated”
Step 10: Stop the program execution

PROGRAM:
WRITING RECORD ON BINARY FILE

import pickle
stud={}
stufile1=open("xiics1.dat","wb")
ans='y'
while ans=='y':
rno=int(input("Enter roll number:"))
name=input("Enter name:")

27
mark1=int(input("Enter English mark:"))

mark2=int(input("Enter Maths mark:"))


mark3=int(input("Enter CS mark:"))
stud["Rollno"]=rno
stud["Name"]=name
stud["Mark1"]=mark1
stud["Mark2"]=mark2
stud["Mark3"]=mark3
pickle.dump(stud,stufile1)
ans=input("Do u want to append more records?(y/n)...?")
stufile1.close()

UPDATING RECORDS IN A BINARY FILE

import pickle
stud={}
found=False
stufile1=open("xiics1.dat","rb+")
print("Student Details")
rno1=int(input("Enter roll number:"))
try:
while True:
rpos=stufile1.tell()
stud=pickle.load(stufile1)
if stud["Rollno"]==rno1:
stud["Mark1"]+=5
stufile1.seek(rpos)
pickle.dump(stud,stufile1)

28
print(stud)
found=True
except:
if found= =False:
print("Record not found")
else:
print("Record updated")
stufile1.close()

Students Details
{'Rollno': 101, 'Name': 'Priya', 'Mark1': 67, 'Mark2': 78, 'Mark3': 89}
{'Rollno': 102, 'Name': 'Yavanesh', 'Mark1': 88, 'Mark2': 90, 'Mark3': 96}
{'Rollno': 103, 'Name': 'Vinoth', 'Mark1': 45, 'Mark2': 90, 'Mark3': 97}
{'Rollno': 104, 'Name': 'Harshi', 'Mark1': 73, 'Mark2': 56, 'Mark3': 90}
{'Rollno': 105, 'Name': 'Chanu', 'Mark1': 66, 'Mark2': 79, 'Mark3': 91}

Student Details
Enter roll number:102
{'Rollno': 102, 'Name': 'Yavanesh', 'Mark1': 93, 'Mark2': 90, 'Mark3': 96}
Record updated

RESULT:
The given program is executed successfully and the result is verified.
29
OUTPUT:
Enter roll number:101
Enter name:Priya
Enter English mark:67
Enter Maths mark:78
Enter CS mark:89
Do u want to append more records?(y/n)...?y
Enter roll number:102
Enter name:Yavanesh
Enter English mark:88
Enter Maths mark:90
Enter CS mark:96
Do u want to append more records?(y/n)...?y
Enter roll number:103
Enter name:Vinoth
Enter English mark:45
Enter Maths mark:90
Enter CS mark:97
Do u want to append more records?(y/n)...?y
Enter roll number:104
Enter name:Harshi
Enter English mark:73
Enter Maths mark:56
Enter CS mark:90
Do u want to append more records?(y/n)...?y
Enter roll number:105
Enter name:Chanu
Enter English mark:66
Enter Maths mark:79
Enter CS mark:91
Do u want to append more records?(y/n)...?n

30
14. CREATE AND SEARCH RECORDS IN A CSV FILE

Create a CSV file with itemno and itemname, price, quantity. Search for a
given itemno number and display the details of item, if not found display
appropriate message.
AIM:
To search a record in a CSV file

ALGORITHM:

Step 1: Start the program execution


Step 2: Import the CSV module and open the file “item.csv” in read mode
Step 3: csv.writer() returns a writer object which writes data into CSV file
Step 4: Use writerobject .writerow() (or) writerobject.writerows() to write one
row or multiplerows of data onto the writer object.
Step 5: csv.reader() returns a reader object which loads data from CSV file
Step 6: Get the itemno from the user
Step 7: Check itemno which is in csv file is equal to the ino which is given by
the user .If thecondition is True go to Step 8 otherwise go to Step 9.
Step 8: Print item details and also print “item is found”
Step 9: Print “Item not found”
Step 10: Stop the program execution

PROGRAM:

WRITING RECORDS ON CSV FILE

import csv
f=open("item.csv","w")
rec=[]
iwriter=csv.writer(f)

31
print("Item Details")
iwriter.writerow(["itemno","iname","quantity","price"])
for i in range(3):
itemno=int(input("Enter itemno:"))
iname=input("Enter item name:")
quantity=int(input("Enter quantity"))
price=int(input("Enter price"))
l=[itemno,iname,quantity,price]
rec.append(l)
iwriter.writerows(rec)
f.close()

SEARCHING A RECORD FROM CSV FILE


import csv
f=open("item.csv","r",newline="\r\n")
ireader=csv.reader(f)
ino=int(input("Enter the itemno to be searched"))
found=False
for i in ireader:
if i[0]==str(ino):
print(i)
found=True
if found==False:
print("Itemno is not found")
else:
print("Itemno is found")
f.close()

RESULT:
The given program is executed successfully and the result is verified.
32
OUTPUT:

Enter itemno:1001
Enter item name:Lux soapEnter quantity: 10
Enter price: 900 Enter itemno:1002
Enter item name:EraserEnter quantity :15
Enter price 200 Enter itemno:1003
Enter item name:Chilli powderEnter quantity: 20
Enter price : 500 Enter itemno:1004
Enter item name:Ice creamEnter quantity :30
Enter price : 450 Enter itemno:1005
Enter item name:Water bottleEnter quantity: 12
Enter price :600

Item Details

['itemno', 'iname', 'quantity', 'price']


['1001', 'Lux soap', '10', '900']
['1002', 'Eraser', '15', '200']
['1003', 'Chilli powder', '20', '500']
['1004', 'Ice cream', '30', '450']
['1005', 'Water bottle', '12', '600']
Enter the itemno to be searched:1004
['1004', 'Ice cream', '30', '450']
Itemno is found

Enter the itemno to be searched:1007Itemno is not found

33
15. STACK OPERATION
Write a Python program to implement a stack using a list data-structure.

AIM:
To implement the stack operation using a list data structure
ALGORITHM:

Step 1: Start the program execution


Step 2: Read the value of choice
Step 3: Check if choice==1, then call the function view( ) – To view the element in
stack , else go to step 4
Step 4: Check if choice==2, then call the function push( ) – To insert an element
into stack,else go to step 5
Step 5: Check if choice==3, then call the function pop( ) – To delete an element
from stack,else go to step 6
Step 6: Check if choice==4, then call the function peek( ) – To display top element
of stack,else go to step 7
Step 7: Print “Wrong choice”
Step 8: Stop the program execution

PROGRAM:

stack=[]
def view( ):
for x in range(len(stack)):
print(stack[x])
def push():
item=int(input("Enter integer value"))
stack.append(item)
def pop():
if(stack==[]):
print("Stack is empty")
else:

34
item=stack.pop(-1)
print("Deleted element:",item)
def peek():
item=stack[-1]
print("Peeked element:",item)
print("Stack operation")
print("************")
print("1.view")
print("2.push")
print("3.pop")
print("4.peek")
while True:
choice=int(input("Enter your choice"))
if choice==1:
view()
elif choice==2:
push( )
elif choice==3:
pop( )
elif choice==4:
peek( )
else:
print("Wrong choice")

RESULT:

The given program is executed successfully and the result is verified.


35
OUTPUT:
Stack operation
************
1.view
2.push
3.pop
4.peek
Enter your choice2
Enter integer value20
Enter your choice2
Enter integer value30
Enter your choice2
Enter integer value40
Enter your choice2
Enter integer value50
Enter your choice2
Enter integer value60
Enter your choice1
20
30
40
50
60
Enter your choice3
Deleted element: 60
Enter your choice4
Peeked element: 50
Enter your choice5
Wrong choice
Enter your choice:

36
MySQL

37
16. Create a Stationary and Consumer table and insert data. Implement the following
SQL commands on the Stationary and Consumer
AIM:

To create two tables for stationary and consumer and execute the given commands using
SQL.

TABLE: STATIONARY

S_ID StationaryName Company Price


DP01 Dot Pen ABC 10
PL02 Pencil XYZ 6
ER05 Eraser XYZ 7
PL01 Pencil CAM 5
GP02 Gel Pen ABC 15

TABLE: CONSUMER

C_ID ConsumerName Address S_ID


01 Good Learner Delhi PL01
06 Write Well Mumbai GP02
12 Topper Delhi DP01
15 Write & Draw Delhi PL02
16 Motivation Bangalore PL01

i) To display the details of those Consumers whose Address is Delhi

ii) To display the details of Stationary whose Price is in the range of 8 to 15(Both
values included)
iii) To display the ConsumerName , Address from table Consumer and Company and

Price from table Stationery with their corresponding matching S_ID


iv) To increase the Price of all Stationary by 2.

v) To display distinct Company from STATIONARY .

38
SQL QUERY:

CREATE TABLE STATIONARY (S_ID char(5) NOT NULL PRIMARY KEY,


StationaryName char(25), Company char(5), Price int);

INSERT INTO STATIONARY VALUES(“DP01” , “Dot Pen”, “ABC”, 10);

INSERT INTO STATIONERY VALUES(“PL02” , “Pencil”, “XYZ”, 6)

CREATE TABLE CONSUMER (C_ID int , ConsumerName char(25)Address char(25),


S_ID char(5));

INSERT INTO CONSUMER VALUES(01, “Good Learner”, “Delhi”, “PL01”);


INSERT INTO CONSUMER VALUES(06,”Write Well”,”Mumbai”,”GP02”);

OUTPUT:
i) Select * from consumer where address=”delhi”;

c_id consumer address S_id


name
1 good delhi PL01
learner
12 topper delhi DP02
15 write & delhi PL02
draw

ii) select * from stationary where price between 8 and 15;

S_id stationary compa price


ny
Dp01 dot pen ABC 10
GP02 gel pen ABC 15

39
iii) select consumername, address, company, price from stationery, consumer
where stationery.s_id=consumer.s_id;
iv)
consumername addres company Price
s
good learner delhi CAM 5
write well mumba ABC 15
i
topper delhi ABC 10
write&draw delhi XYZ 6
motivation bangal CAM 5
ore

v) update stationery set price=price+2;select * from stationery;

S_id stationary company Price


DP01 Dot pen ABC 12
PL02 Pencil XYZ 8
ER05 Eraser XYZ 9
PL01 Pencil CAM 7
GP02 Gel pen ABC 17

vi) select distinct(company) from stationery;

Company
ABC
XYZ
CAM

40
17. Create a Item and Traders table and insert data. Implement the following SQL
commands on the Item and Traders

AIM:

To create two tables for item and traders and execute the given commands using
SQL.

TABLE:ITEM

Code IName Qty Price Company TCode


1001 DIGITAL PAD 120 11000 XENTIA T01
121
1006 LED SCREEN 40 70 38000 SANTORA T02
1004 CAR GPS 50 2150 GEOKNO T01
SYSTEM W
1003 DIGITAL 160 8000 DIGICLIC T02
CAMERA 12X K
1005 PEN DRIVE 600 1200 STOREHO T03
32GB ME

TABLE:TRADERS

TCode TName City


T01 ELECTRONICS SALES MUMBAI
T03 BUSY STORE CORP DELHI
T02 DISP HOUSE INC CHENNAI

i) To display the details of all the items in ascending order of item names (i.e IName)

ii) To display item name and price of all those items, whose price is in the range of10000

and 22000 (both values inclusive)


iii) To display the number of items, which are traded by each trader? The expected output

ofthis query should be


T01 2
T02 2
T03 1
iv) To display the Price , item name(i.e IName) and quantity(i.e Qty) of those items which

41
have quantity more than 150.
v) To display the names of those traders, who are either from DELHI or from
MUMBAI.CREATE TABLE ITEM(Code int , IName char(25) , Qty int , Price int ,
Company
char(25),TCode char(5));

INSERT INTO ITEM VALUES(1001,”DIGITAL PAD 121”,120, 11000,”XENTIA”,


“T01”);INSERT INTO ITEM VALUES(1006,”LED SCREEN 40”,70,
38000,”SANTORA”, “T02”);

CREATE TABLE TRADERS(TCode char(5) , TName char(25), City char(20));


INSERT INTO TRADERS VALUES(“T01”,”ELECTRONICS SALES”,”MUMBAI”);
INSERT INTO TRADERS VALUES( “T03”,”BUSY STORE CORP”,”DELHI”);

OUTPUT:
i) select * from ITEM order by IName;

Code IName Qty Price Company TCode


1004 CAR GPS 50 2150 GEOKNOW T01
SYSTEM
1003 DIGITAL 160 8000 DIGICLICK T02
CAMERA 12X
1001 DIGITAL PAD 120 11000 XENTIA T01
121
1006 LED SCREEN 70 38000 SANTORA T02
1005 PEN DRIVE 600 1200 STORE T03
32GB HOME

ii) select IName , Price from ITEM where Price between 10000 and 22000;

IName Price
DIGITAL PAD 121 11000
iii) select TCode , count(*) from ITEM group by TCode;

Tcode Count(*)
T01 2
T02 2
T03 1

42
iv) select Price , IName , Qty from ITEM where Qty>150;

Price IName Qty


8000 DIGITAL 160
CAMERA 12X
1200 PEN DRIVE 32GB 600

v) select TName from TRADERS where City in (“DELHI”,”MUMBAI”);

TName
ELECTRONICS SALES
BUSY STORE CORP

RESULT:

The given program is executed successfully and the result is verified.

43
18. Create a Doctors and Salary table and insert data. Implement the following
SQL commands on the Doctors and Salary

AIM:
To create two tables for doctor and salary and execute the given commandsusing
SQL.

TABLE:DOCTOR

ID NAME DEPT SEX EXPERIENCE


101 John ENT M 12
104 Smith ORTHOPEDIC M 5
107 George CARDIOLOGY M 10
114 Lara SKIN F 3
109 K George MEDICINE F 9
105 Johnson ORTHOPEDIC M 10
117 Lucy ENT F 3
111 Bill MEDICINE F 12
130 Morphy ORTHOPEDIC M 15

TABLE: SALARY
ID BASIC ALLOWANCE CONSULTATION
101 12000 1000 300
104 23000 2300 500
107 32000 4000 500
114 12000 5200 100
109 42000 1700 200
105 18900 1690 300
130 21700 2600 300

i) Display NAME of all doctors who are in “MEDICINE” having more than 10 years

experience from table DOCTOR


ii) Display the average salary of all doctors working in “ENT” department using the tables

DOCTOR and SALARY. (Salary=BASIC+ALLOWANCE)


iii) Display minimum ALLOWANCE of female doctors.

iv) Display DOCTOR.ID , NAME from the table DOCTOR and BASIC , ALLOWANCE
from the table SALARY with their corresponding matching ID.
v) To display distinct department from the table doctor.

44
CREATE TABLE DOCTOR(ID int NOT NULL PRIMARY KEY, NAME char(25) , DEPT
char(25) , SEX char , EXPERIENCE int);

INSERT INTO DOCTOR VALUES(101,”John”, “ENT”,‟M‟,12);


INSERT INTO DOCTOR VALUES(104,”Smith”, “ORTHOPEDIC”,‟M‟,5);

CREATE TABLE SALARY(ID int, BASIC int, ALLOWANCE int, CONSULTATION


int);INSERT INTO SALARY VLAUES(101, 12000,1000,300);
INSERT INTO SALARY VLAUES(104, 23000,2300,500);

OUTPUT:

i) select NAME from DOCTOR where DEPT=”MEDICINE” and EXPERIENCE >10;

NAME
Bill

ii) select avg(BASIC+ALLOWANCE) “avg salary” from DOCTOR , SALARY where


DOCTOR.ID=SALARY.ID and DEPT=”ENT”;

Avg salary
13000.00

iii) select min(ALLOWANCE) from SALARY, DOCTORwhere SEX=‟F‟ and


DOCTOR.ID=SALARY.ID;

min(ALLOWANCE)
1700

45
iv) select DOCTOR.ID, NAME, BASIC ,ALLOWANCE from DOCTOR,SALARYwhere
DOCTOR.ID=SALARY.ID;

ID NAME BASIC ALLOW


ANCE
101 John 12000 1000
104 Smith 23000 2300
107 George 32000 4000
109 K George 42000 1700
114 Lara 12000 5200
130 Morphy 21700 2600

v) select distinct(DEPT) from DOCTOR;

DEPT
ENT
ORTHOPEDIC
CARDIOLOGY
SKIN
MEDICINE

RESULT:

The given program is executed successfully and the result is verified.


46
19. Create a Company and customer table and insert data. Implement the following
SQL commands on the company and customer

AIM:

To create two tables for company and customer and execute the given commands
usingSQL.

TABLE : COMPANY

TABLE : CUSTOMER

1. To display those company name which are having price less than 30000.

2. To display the name of the companies in reverse alphabetical order.

3. To increase the price by 1000 for those customers whose name starts with „S‟

4. To add one more column total price with decimal (10,2) to the table customer

5. To display the details of company where product name as mobile.

47
CREATE TABLE COMPANY(cid int(3) , name varchar(15) , city varchar(10),
productname varchar(15));
INSERT INTO COMPANY VALUES(111, „SONA‟, „DELHI‟, „TV‟);

CREATE TABLE CUSTOMER(custid int(3), name varchar(15), price int(10),qty int(3) ,


cid int(3));

INSERT INTO CUSTOMER VALUES(101, „ROHAN SHARMA‟, 70000,20,222);

OUTPUT:

1. select name from company where company.cid=customer. cid andprice < 30000;

NAME
NEHA SONI

2. select name from company order by name desc;

NAME
SONY
ONIDA
NOKIA
DELL
BLACKBERRY
3. update customer set price = price + 1000 where name like „s%‟;select * from customer;

CUSTID NAME PRICE QTY CID

101 ROHAN SHARMA 70000 20 222


102 DEEPAK KUMAR 50000 10 666
103 MOHAN KUMAR 30000 5 111
104 SAHIL BANSAL 36000 3 333
105 NEHA SONI 25000 7 444
106 SONA AGARWAL 21000 5 333
107 ARUN SINGH 50000 15 666

48
alter table customer add totalprice decimal(10,2);Select * from customer;
CUS ID PRICE QTY CID TOTAL
NAME
PRICE
101 ROHAN SHARMA 70000 20 222 NULL
4. s102 DEEPAK KUMAR 50000 10 666 NULL
e103 MOHAN KUMAR 30000 5 111 NULL
l104 SAHIL BANSAL 36000 3 333 NULL
e105 NEHA SONI 25000 7 444 NULL
c106 SONA AGARWAL 21000 5 333 NULL
t107 ARUN SINGH 50000 15 666 NULL

* from company where productname=‟mobile‟;

CID NAME CITY PRODUCT NAME

222 NOKIA MUMBAI MOBILE


444 SONY MUMBAI MOBILE
555 BLACKBERRY MADRAS MOBILE

RESULT:

The given program is executed successfully and the result is verified.

49
20. SQL :TEACHER (RELATION)

AIM: To create table for teacher and execute the given commands using SQL.

TABLE : TEACHER

No Name Ag Departm DateofJo Salary Sex


e ent in
1 Jishnu 34 Computer 10/01/97 12000 M
2 Sharmila 31 History 24/03/98 20000 F
3 Santhosh 32 Maths 12/12/96 30000 M
4 Shanmathi 35 History 01/07/99 40000 F
5 Ragu 42 Maths 05/09/97 25000 M
6 Shiva 50 History 27/02/97 30000 M
7 Shakthi 44 Computer 25/02/97 21000 M
8 Shriya 33 Maths 31/07/97 20000 F

1. To show all information about the teacher of history department.

2. To list the names of female teacher who are in Maths department.

3. To list names of all teachers with their date of joining in ascending order.

4. To count the number of teachers with age>35.

5. To count the number of teachers department wise.

CREATE TABLE TEACHER(No int(2), Name varchar(15), Age int(3) , Department


varchar(15), Dateofjoin varchar(15) , Salary int(7) , Sex char(1));

INSERT INTO TEACHER VALUES(1,‟Jishnu‟,34,‟Computer‟,‟10/01/97‟,12000,‟M‟);

OUTPUT:
1. select * from teacher where Department=‟History‟;

No Name Age Departm DateofJo Salary Se


ent in x
2 Sharmila 31 History 24/03/98 20000 F
4 Shanmat 35 History 01/07/99 40000 F
hi
6 Shiva 50 History 27/02/97 30000 M

50
2. select Name from teacher where Department=‟Maths‟ and Sex=‟F‟;

Name
Shriya

3. select Name , Dateofjoin from teacher order by Dateofjoin asc;

Name Dateofjoin
Santhosh 12/12/96
Jishnu 10/01/97
Shakthi 25/02/97
Shiva 27/02/97
Shriya 31/07/97
Ragu 05/09/97
Sharmila 24/03/98
Shanmathi 01/07/99

4. select count(*) from teacher where Age>35;

count(*)
3

5. select Department , count(*) from teacher group by department;

Department count
(*)
Computer 2
History 3
Maths 3

RESULT:

The given program is executed successfully and the result is verified.


51
21. INTEGRATE PYTHON WITH SQL - FETCHING RECORDS FROM TABLE

AIM:

To integrate SQL with Python by importing the MySQL module and extracting data
fromresult set

PROGRAM:

import mysql.connector as sqltor


mycon=sqltor.connect(host=”localhost”, user=”root”, password=”root”,
databse=”ssps”)
if mycon.is_connected( ) = = False:
print(“Error connecting to MySQL database”)
cursor=mycon.cursor( )
cursor.execute(“select * from student”)
data=cursor.rowcount(3) count=cursor.rowcount
for row in data:
print(row)
mycon.close( )

OUTPUT:

(1001, “Vinusha”, 50,70, 80 , “Namakkal”)


(1001, “Aswin”, 54,82, 85 , “Erode”)
(1001, “Bheem”, 90,73, 78 , “Salem”)

RESULT:

The given program is executed successfully and the result is verified

52
22, INTEGRATE PYTHON WITH SQL - COUNTING RECORDS FROM TABLE

AIM:

To integrate SQL with Python by importing the MySQL module and extracting data
fromresult set

PROGRAM:

import mysql.connector as sqltor


mycon=sqltor.connect(host=”localhost”, user=”root”, password=”root”,
databse=”ssps”)
if mycon.is_connected( ) = = False:
print(“Error connecting to MySQL database”)
cursor=mycon.cursor( )
cursor.execute(“select * from student”)
data=cursor.fetchone( )
count=cursor.rowcount
print(“Total number of rows retrieved from resultset :”, count)
data=cursor.fetchone( )
count=cursor.rowcount
print(“Total number of rows retrieved from resultset :”, count)
data=cursor.fetchmany(3)
count=cursor.rowcount
print(“Total number of rows retrieved from resultset :”, count)

RESULT:

The given program is executed successfully and the result is verified.


53
OUTPUT:

Total number of rows retrieved from resultset : 1


Total number of rows retrieved from resultset : 2
Total number of rows retrieved from resultset : 5

54
23. INTEGRATE SQL WITH PYTHON - SEARCHING A RECORD FROM TABLE

AIM:

Integrate SQL with Python by importing the MySQL module to search an


employee using eno ,if it is present in table display the record

PROGRAM:

import mysql.connector as mc
mycon=mc.connect(host='localhost',user='root',password='ssps',data base='db12')
if mycon.is_connected( ):
print("Py->Sql connected")
eno=int(input("Enter num:"))
mcursor=mycon.cursor( )
mcursor.execute("select * from emp")
allrow=mcursor.fetchall( )
for row in allrow:
if row[0]==eno:
print(row)
mycon.commit( )
mycon.close( )

RESULT:

The given program is executed successfully and the result is verified.

55
OUTPUT:
Py-> sql is connected
Enter num : 103
(103,‟Cinu , 43, „Namakkal‟)

56
24. INTEGRATE SQL WITH PYTHON - DELETING A RECORD FROM TABLE

AIM:

To integrate SQL with Python by importing the MySQL module to search a student
using rollno and delete the record.

PROGRAM :

import mysql.connector as mc
mycon=mc.connect(host='localhost',user='root',password='ssps',database='db12')
if mycon.is_connected():
print("Py->Sql connected")
eno=int(input("Enter num:"))
mcursor=mycon.cursor()
mcursor.execute("select * from emp")
allrow=mcursor.fetchall()
for row in allrow:
if row[0]==eno:
mcursor.execute("delete from emp where eno={}".format(eno))
mcursor.execute("select * from emp")
print(mcursor.fetchall())
mycon.commit()
mycon.close()

RESULT:
The given program is executed successfully and the result is verified.

57
OUTPUT:

Py -> sql is connected


Enter num : 102 (101,‟Anu‟,23,‟Salem‟)
(103,‟Cinu‟,43,‟Namakkal‟)
(104, „Nishanth‟, 46,‟Chennai‟)
(105, „Nanda‟, 56, „Erode‟)

58

You might also like