Xii CS 2023 Practical Programs
Xii CS 2023 Practical Programs
AIM:
To find the factorial value for the given number
ALGORITHM:
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
2
2. FIBONACCI SERIES
AIM:
ALGORITHM:
RESULT:
3
OUTPUT:
of n : 5
Fibonacci
Series :
4
3. STRING PALINDROME
notAIM:
ALGORITHM:
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:
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:
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
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
AIM:
To read a text file myfile.txt line by line and display each word separated by a #.
ALGORITHM:
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()
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:
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:"))
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:
PROGRAM:
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()
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
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:
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:
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
TABLE: CONSUMER
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
38
SQL QUERY:
OUTPUT:
i) Select * from consumer where address=”delhi”;
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
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
TABLE:TRADERS
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
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));
OUTPUT:
i) select * from ITEM order by IName;
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;
TName
ELECTRONICS SALES
BUSY STORE CORP
RESULT:
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
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
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);
OUTPUT:
NAME
Bill
Avg salary
13000.00
min(ALLOWANCE)
1700
45
iv) select DOCTOR.ID, NAME, BASIC ,ALLOWANCE from DOCTOR,SALARYwhere
DOCTOR.ID=SALARY.ID;
DEPT
ENT
ORTHOPEDIC
CARDIOLOGY
SKIN
MEDICINE
RESULT:
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.
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
47
CREATE TABLE COMPANY(cid int(3) , name varchar(15) , city varchar(10),
productname varchar(15));
INSERT INTO COMPANY VALUES(111, „SONA‟, „DELHI‟, „TV‟);
OUTPUT:
1. select name from company where company.cid=customer. cid andprice < 30000;
NAME
NEHA SONI
NAME
SONY
ONIDA
NOKIA
DELL
BLACKBERRY
3. update customer set price = price + 1000 where name like „s%‟;select * from customer;
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
RESULT:
49
20. SQL :TEACHER (RELATION)
AIM: To create table for teacher and execute the given commands using SQL.
TABLE : TEACHER
3. To list names of all teachers with their date of joining in ascending order.
OUTPUT:
1. select * from teacher where Department=‟History‟;
50
2. select Name from teacher where Department=‟Maths‟ and Sex=‟F‟;
Name
Shriya
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
count(*)
3
Department count
(*)
Computer 2
History 3
Maths 3
RESULT:
AIM:
To integrate SQL with Python by importing the MySQL module and extracting data
fromresult set
PROGRAM:
OUTPUT:
RESULT:
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:
RESULT:
54
23. INTEGRATE SQL WITH PYTHON - SEARCHING A RECORD FROM TABLE
AIM:
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:
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:
58