Nothing Special   »   [go: up one dir, main page]

Cs Xii Practical File

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

JAGANNATH VIDYALAYA

Affiliation No. : 1930352


Thaiyur, Near Kelambakkam, Off OMR, Chennai – 603 103.
Admin Office : 4, 1st Cross Street, R.A. Puram, Chennai – 600 028.

____________________ RECORD

Certified to be the Bonafide Record of work done By


…………………………………………………………………… of class
............................................................................................................. in
the ….………………………………………………….. of JAGANNATH
VIDYALAYA CHENNAI, during the year …………………...

Date : Teacher-in-charge

REGISTER NO ……………………………………………

Submitted for Practical Examination held on …….....................…………...............................................


at JAGANNATH VIDYALAYA, CHENNAI – 603 103

Principal Internal Examiner External Examiner

1
PRACTICAL INDEX

S.NO CONTENT
1 FACTORIAL OF A GIVEN NUMBER
2 FIBONACCI SERIES
3 STRING PALINDROME
OCTAL TO OTHER EQUIVALENT NUMBER CONVERSION
4 USING FUNCTION
CREATING A MENU DRIVEN PROGRAM TO FIND AREA OF
5 CIRCLE,RECTANGLE AND TRIANGLE
6 SUM OF ALL THE ELEMENTS OF A LIST
MENU DRIVEN PROGROM TO PERFORM ARITHMETIC
7 OPERATORS
8 RANDOM NUMBER GENERATION
9 READ A FILE LINE BY LINE
10 COPYING LINES IN A FILE
WRITE A PYTHON PROGRAM TO READ A TEXT FILE AND
DISPLAY THE NUMBER OF
11 VOWELS/CONSONANTS/UPPERCASE/LOWERCASE
CHARACTERS IN THE FILE
12 CREATE AND SEARCHING RECORDS IN A BINARY FILE
13 CREATING AND UPDATING RECORDS IN A BINARY FILE
14 CREATE AND SEARCH RECORDS IN A CSV FILE
15 STACK OPERATION
CREATE A STATIONARY AND CONSUMER TABLE AND
16 INSERT DATA. IMPLEMENT THE FOLLOWING SQL
COMMANDS ON THESTATIONARY AND CONSUMER
CREATE A ITEM AND TRADERS TABLE AND INSERT DATA.
17 IMPLEMENT THE FOLLOWING SQL COMMANDS ON THE
ITEMAND TRADERS
CREATE A DOCTORS AND SALARY TABLE AND INSERT
18 DATA.IMPLEMENT THE FOLLOWING SQL COMMANDS ON
THE DOCTORS AND SALARY
19 CREATE A COMPANY AND CUSTOMER TABLE AND INSERT
2
DATA. IMPLEMENT THE FOLLOWING SQL COMMANDS ON
THE COMPANY AND CUSTOMER
20 MYSQL :TEACHER (RELATION)

21 IIINTEGRATE PYTHON WITH SQL - FETCHING RECORDS


FROMTABLE
22 I INTEGRATE PYTHON WITH SQL - COUNTING RECORDS
FROMTABLE
23 INTEGRATE SQL WITH PYTHON - SEARCHING A RECORD
FROMTABLE
24 I INTEGRATE SQL WITH PYTHON - DELETING A RECORD
FROMTABLE

3
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 executionStep


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 7Step6: Calculate
fact =fact*i
Step 7: Return fact to resultStep 8: Print resultStep 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)

OUTPUT:

Please enter any number to find factorial: 5The


factorial of 5 is: 120
RESULT:

4
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 executionStep


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 7Step 5: Print
sum
Step 6: Increment count by 1 and assign a=b, b=sum and sum=a+bStep 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

OUTPUT:

Enter the value of n : 5


Fibonacci Series :

5
0

RESULT:

6
3. STRING PALINDROME

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


AIM:
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
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 True
s=input("Enter string:")
ans = isPalindrome(s)if
(ans):
print("The given string is Palindrome")

7
else:

print("The given string is not a Palindrome")

OUTPUT:

Enter string: madam

The given string is PalindromeEnter string: computerThe given


string is not a Palindrome

RESULT:

8
4. OCTAL TO OTHER EQUIVALENT NUMBER CONVERSION USINGFUNCTION

Write a function that receives an octal number and prints the equivalent numberinother
number bases i.e., in decimal , binary and hexadecimal equivalents.
AIM:

To convert from octal to other equivalent number

ALGORITHM:

Step 1: Start the program executionStep


2: Read the value of num
Step 3: Call the function oct2others

Step 4: Convert passed octal value n to other equivalent number i.e., in


decimal,binary,hexadecimal and print it.
Step 5: Stop the program execution

PROGRAM:

def oct2others(n):

print("passed octal number:",n)


numstring=str(n) decNum=int(numstring,8)
print("Number in Decimal:",decNum)
print("Number in Binary:",bin(decNum))
print("Number in Hexadecimal:",hex(decNum))
num=int(input("Enter an octal number:"))
oct2others(num)

9
OUTPUT:

Enter an octal number:7 passed


octal number: 7 Number in
Decimal: 7 Number in Binary:
0b111 Number in Hexadecimal:
0x7

RESULT:

10
5. 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 andTriangle.using function.

ALGORITHM:

Step 1: Start the program executionStep 2: Read


the choice value
Step 3: If ch==1 , call the function Circle(a) then print area of the circle. Elsegoto Step 4
Step 4: If ch==2 ,call the function Rectangle(L,B) then print area of therectangle .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)

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)

11
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")

OUTPUT:

a. Area of Circle

b. Area of Rectangle

c. Area of Triangle
Enter your choice1
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 Areaof
rectangle is: 35

RESULT:

12
6. SUM OF ALL THE ELEMENTS OF A LIST

Write a Python program using function to find the sum of all elements of a list.

Aim:

To write a Python program using function to find the sum of all elements of alist.

Algorithm:

Step 1: Start
Step 2: Create user defined function name sum_list write following stepsSum=0
For I in items:

Sum=sum+i

Return the sum value


Step 3: Read x value from user.
Step 4: Call the sum_list()Step
5: Print the result.
Step 6: Stop

Program:

def sum_list(items):
sum=0
for i in items: sum=sum+i
return sum lst=eval(input("Enter list
items: "))
print("Sum of list items is : ",sum_list(lst))OUTPUT:
ENTER LIST ITEMS
[2,4,6,8]
Sum of list items is 20

RESULT:

13
7. MENU DRIVEN PROGROM TO PERFOR M ARITHMETIC OPERATORS

To write a python program to create a menu driven program to perform arithmeticoperations.

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 programStep 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 5Step 5 : If choice=3,
calculate c=a*b , otherwise goto step 6Step 6 : If choice=4, calculate
c=a/6 , otherwise goto step 7
Step 7 : print “Invalid option” Step 8: Stop the execution of the programProgram:
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")

14
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

15
OUTPUT:

******************
ARITHMETIC OPERATIONS
1. Addition

2. Subtraction

3. Multiplication

4. Division

Enter your choice1 Enter


the first number23
Enter the second number34The
sum is 57
Enter your choice2 Enter
the first number34
Enter the second number23The
difference is 11
Enter your choice3 Enter
the first number5
Enter the second number4The
product is 20
Enter your choice4 Enter
the first number32
Enter the second number8The
remainder is 4.0 Enter your
choice5
Please enter your correct choice

RESULT:

16
8. RANDOM NUMBER GENERATION

Write a Python program for random number generation that generates randomnumbers 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 generatenumber from 1
to 6 using randint() method.

Step 4: Print the random generate numberStep 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!!")


Output:

Enter any number: 2


Too low
17
Enter number again: 4
Too high!
Enter number again: 3you
guessed it right!!

RESULT:

18
9. READ A FILE LINE BY LINE

Write a program in Python to read a text file myfile.txt line by line and display eachwordseparated
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 7Step 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 3Step 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()

OUTPUT:

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

19
10. COPYING LINES IN A FILE

Copy all the lines that contain the character `a' in a file and write it to anotherfile.
AIM:

To Copy all the lines that contain the character `a' in a file and write it toanother 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 step9
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 3Step 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 elsego 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( )
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.

20
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() methodStep 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() methodStep 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=0for
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

21
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 toconvert a
program written in assembly or hign=level language to machine Languang to Machine
Language
Output:
('Vowels are :', 58)

('Consonants :', 90)

('Lower_case_letters :', 143)

('Upper_case_letters :', 5)
RESULT:

22
12. CREATE AND SEARCHING RECORDS IN A BINARY FILE

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

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 modeStep 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 5else 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()

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)...?yEnter
roll number:1002
Enter name:Rani Enter
English mark:90Enter
Maths mark:85 Enter CS

24
mark:86
Do u want to append more records?(y/n)...?yEnter
roll number:1003
Enter name:Vishnu Enter
English mark:67Enter
Maths mark:78 Enter CS
mark:89
Do u want to append more records?(y/n)...?yEnter
roll number:1004
Enter name:Rishi Enter
English mark:92Enter
Maths mark:67 Enter CS
mark:84
Do u want to append more records?(y/n)...?yEnter
roll number:1005
Enter name:Seetha Enter English mark:86Enter
Maths mark:59
Enter CS mark:70
Do u want to append more records?(y/n)...?n

25
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:

26
13. CREATING AND UPDATING RECORDS IN A BINARY FILE

Write a Python program to create a binary file with roll number, name andmarks. 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 modeStep 3: Read
the student details using load function
Step 4: Check if stud[“Rollno”] = =rno1, if the condition is true go to step 5 elsego to step 7
Step 5: Update stud[“Mark1”]+=5 and set the file pointer to write updatedrecord 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 10Step 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)

print(stud)
found=True
except:

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

28
OUTPUT:
Enter roll number:101
Enter name:Priya Enter
English mark:67Enter
Maths mark:78 Enter CS
mark:89
Do u want to append more records?(y/n)...?yEnter
roll number:102
Enter name:Yavanesh Enter
English mark:88Enter Maths
mark:90 Enter CS mark:96
Do u want to append more records?(y/n)...?yEnter
roll number:103
Enter name:Vinoth Enter
English mark:45Enter
Maths mark:90 Enter CS
mark:97
Do u want to append more records?(y/n)...?yEnter
roll number:104
Enter name:Harshi Enter
English mark:73Enter
Maths mark:56 Enter CS
mark:90
Do u want to append more records?(y/n)...?yEnter
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

29
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:

30
14. CREATE AND SEARCH RECORDS IN A CSV FILE

Create a CSV file with itemno and itemname, price, quantity. Search for agiven 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 onerow or multiplerows of data onto the
writer object.
Step 5: csv.reader() returns a reader object which loads data from CSV fileStep 6: Get the
itemno from the user
Step 7: Check itemno which is in csv file is equal to the ino which is given bythe 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)

print("Item Details")
iwriter.writerow(["itemno","iname","quantity","price"]) for i in
range(3):
itemno=int(input("Enter itemno:"))
31
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()

32
OUTPUT:

Enter itemno:1001

Enter item name:Lux soapEnter quantity: 10Enter


price: 900 Enter itemno:1002
Enter item name:EraserEnter quantity :15Enter
price 200 Enter itemno:1003
Enter item name:Chilli powderEnter quantity: 20Enter
price : 500 Enter itemno:1004
Enter item name:Ice creamEnter quantity :30Enter
price : 450 Enter itemno:1005
Enter item name:Water bottleEnter quantity: 12Enter
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
RESULT:

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 executionStep


2: Read the value of choice
Step 3: Check if choice==1, then call the function view( ) – To view the element instack ,else go to
step 4
Step 4: Check if choice==2, then call the function push( ) – To insert an elementinto stack,else
go to step 5
Step 5: Check if choice==3, then call the function pop( ) – To delete an elementfrom stack,else
go to step 6
Step 6: Check if choice==4, then call the function peek( ) – To display top elementof 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")

35
OUTPUT:
Stack operation
************
1.view
2.push
3.pop
4.peek
Enter your choice2 Enter
integer value20Enter
your choice2 Enter
integer value30Enter
your choice2 Enter
integer value40Enter
your choice2 Enter
integer value50Enter
your choice2 Enter
integer value60Enter
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

RESULT:

33
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
valuesincluded)
iii) To display the ConsumerName , Address from table Consumer and Company andPricefrom
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 .

34
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

35
iii) select consumername, address, company, price from stationery, consumerwhere
stationery.s_id=consumer.s_id;
iv)
consumername address company Price

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

36
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 of10000and 22000
(both values inclusive)
iii) To display the number of items , which are traded by each trader. The expectedoutput ofthis query
should be
T01 2
37
T02 2
T03 1

iv) To display the Price , item name(i.e IName) and quantity(i.e Qty) of those itemswhich

have quantity more than 150.

v) To display the names of those traders, who are either from DELHI or fromMUMBAI.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
38
iii) select TCode , count(*) from ITEM group by TCode;

Tcode Count(*)
T01 2
T02 2
T03 1

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:

39
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 commands
usingSQL

SSTABLE: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 yearsexperience
from table DOCTOR
ii) Display the average salary of all doctors working in “ENT” department using the tablesDOCTOR and
SALARY. (Salary=BASIC+ALLOWANCE)

40
iii) Display minimum ALLOWANCE of female doctors.

iv) Display DOCTOR.ID , NAME from the table DOCTOR and BASIC , ALLOWANCEfromthe table
SALARY with their corresponding matching ID.

v) To display distinct department from the table doctor.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, CONSULTATIONint);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

41
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:

42
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 Se


e ent in x
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) , Departmentvarchar(15),


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

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

43
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

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:

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

AIM:

To integrate SQL with Python by importing the MySQL module and extracting datafromresult 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.rowcountfor 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:

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

AIM:

To integrate SQL with Python by importing the MySQL module and extracting datafromresult 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)

OUTPUT:

Total number of rows retrieved from resultset : 1Total


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

RESULT:

46
23. INTEGRATE SQL WITH PYTHON - SEARCHING A RECORD FROM TABLE
AIM:

Integrate SQL with Python by importing the MySQL module to search anemployee 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( )

OUTPUT:
Py-> sql is connected
Enter num : 103
(103,’Cinu , 43, ‘Namakkal’)

RESULT:

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

AIM:

To integrate SQL with Python by importing the MySQL module to search a studentusing 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() OUTPUT:

Py -> sql is connected

Enter num : 102 (101,’Anu’,23,’Salem’)


(103,’Cinu’,43,’Namakkal’)
(104, ‘Nishanth’, 46,’Chennai’)

(105, ‘Nanda’, 56, ‘Erode’)

RESULT:

48

You might also like