Cs Practical New-Final
Cs Practical New-Final
CLASS -XII
q1: Input any number from user and calculate factorial of a number
num = int(input("Enter any number :"))
fact = 1
a=1
while a<=num :
fact = fact * a
a=a+1
print("Factorial of ", num , " is :",fact)
OUTPUT
Enter any number :6
Factorial of 6 is : 720
==============================================================================
q2:Write a Python program for random number generation that generates random
numbers between 1 to 6 (simulates a dice).
import random
while True :
choice=input("Enter 'r' to roll dice or press any other key to quit: ")
if(choice!="r"):
break
n=random.randint(1,6)
print(n)
OUTPUT
Enter 'r' to roll dice or press any other key to quit: r
4
Enter 'r' to roll dice or press any other key to quit: r
3
Enter 'r' to roll dice or press any other key to quit:
==============================================================================
Q3: Input any number from user and check it is Prime no. or not
Output:
==============================================================================
Q5: Write a python Program to enter two numbers and print the
arithmetic operations like +,-,*, /, // and %.
Output:
==============================================================================Q 6: Write
a python program to Computing the area of triangle and circle .
def tarea(b,h):
a=½ *b*h
return a
def carea(r):
a = 22/7 * r *r
return a
while(1):
print(" Menu")
print("1. Area of Triangle")
print("2. Area of Circle")
print("3. Exit")
ch = int(input("Enter your choice:"))
if(ch==1):
b = float(input("Enter the base of triangle : "))
h = float(input("Enter the height of triangle : "))
print("The area of triangle : ", tarea(b,h))
elif(ch==2):
r = float(input("Enter the radius of circle :"))
print("The area of circle :", carea(r))
elif (ch==3):
break
else:
print("Wrong Choice")
OUTPUT
Menu
1.Area of triangle
2.Area of Circle
3.Exit
Enter your choice 2
Enter the radius of circle:1
The area of circle:3.14159
Menu
1.Area of triangle
2.Area of Circle
3.Exit
Enter your choice 1
Enter the base of triangle :10
Enter the height of triangle : 5
The area of triangle : 25.0
Menu
1.Area of triangle
2.Area of Circle
3.Exit
Enter your choice 3
==============================================================================
Q7: Write a python Program to search any word in a given sentence.
def countWord(str1,word):
s = str1.split()
count=0
for w in s:
if w==word:
count+=1
return count
str1 = input("Enter any sentence :")
word = input("Enter word to search in sentence :")
count = countWord(str1,word)
if count==0:
print("## Sorry! ", word," not present ")
else:
print("## ",word," occurs ",count," times ## ")
OUTPUT
Enter any sentence :my computer your computer our computer everyones computer
Enter word to search in sentence :computer
## computer occurs 4 times ##
>>>
Enter any sentence :learning python is fun
Enter word to search in sentence :java
## Sorry! java not present
==============================================================================
Q8: Write a python Program to read and display file content line by line with each word
separated by "#‟
f = open("file1.txt")
for line in f:
words = line.split()
for w in words:
print(w +'#',end='')
print()
f.close()
input:
if the original content of file is:
India is my country I
love python
Python learning is fun
OUTPUT
India#is#my#country#
I#love#python#
Python#learning#is#fun#
=========================================================================
Q 9: Write a python Program to merge two dictionaries
Output:
None
{‘d’:6,'c': 4, 'a': 10, 'b': 8 }
==========================================================================
10: Write a python Program to add two matrices using nested loop.
Output:
==============================================================================
11: Write a python Program to read the content of file and display the total number of
Consonants, uppercase, vowels and lowercase characters.‟
f = open("file1.txt")
v=c= u= l=0
data = f.read()
for ch in data:
if ch.isalpha():
if ch.lower() in “aeiou”:
v+=1
else:
c+=1
if ch.isupper():
u+=1
elif ch.islower():
l+=1
print("Total Vowels in file :", v)
print("Total Consonants in file :",c)
print("Total Capital letters in file :",u)
print("Total Small letters in file :",l)
f.close()
input:
OUTPUT
Total Vowels in file : 16
Total Consonants in file : 30
Total Capital letters in f ile : 2
Total Small letters in file : 44
=================================================
Q12: Program to read the content of file line by line and write it to another file
except for that lines contains "a‟ letter in it.
f1 = open("file2.txt")
f2 = open("file2copy.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print(“## File Copied Successfully! ##”)
f1.close()
f2.close()
INPUT:
Content of file2.txt
a quick brown fox
one two three four five six seven
India is my country
eight nine ten
bye!
OUTPUT
==============================================================================
Q13: Program to create binary file to store Rollno and Name, Search any Rollno and
display name if Rollno found otherwise “Rollno not found”
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
student.append([roll,name])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb')
student=[]
while True:
try:
student = pickle. load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to search :"))
for s in student:
if s[0]==r:
print("## Name is :",s[1], " ##")
found=True
break
if f o u n d = = F a l s e :
print("####Sorry! Roll number not found ####")
ans=input("Search more ?(Y) :")
f.close()
OUTPUT
import pickle
student=[]
f=open('student.dat','wb')
ans='y'
while ans.lower()=='y':
roll = int(input("Enter Roll Number :"))
name = input("Enter Name :")
marks = int(input("Enter Marks :"))
student.append([roll,name,marks])
ans=input("Add More ?(Y)")
pickle.dump(student,f)
f.close()
f=open('student.dat','rb+')
student=[]
while True:
try:
student = pickle.load(f)
except EOFError:
break
ans='y'
while ans.lower()=='y':
found=False
r = int(input("Enter Roll number to update :"))
for s in student:
if s[0]==r:
m = int(input("Enter new marks :"))
s[2]=m
print("## Record Updated ##")
found=True
break
if not found:
print("####Sorry! Roll number not found ####")
ans=input("Update more ?(Y) :")
f.close()
OUTPUT
==============================================================================
Q15: Write a Python script to write VOTER.CSV file containing Voter_Id, VoterName, VoterAge having
comma as a delimiter. Display those records where voter age is more than 65.
import csv
f=open("VOTER.csv","w",newline="")
a=csv.writer(f)
a.writerow(["Voter_ID","VoterName","VoterAge"])
a.writerow(["ABZ1234560","Rajeev","67"])
a.writerow(["AHZ1234870","Sonali","72"])
a.writerow(["BJZ1234350","Ankita","27"])
a.writerow(["CBK9834560","Gaurav","21"])
f.close()
f=open("VOTER.csv", "r", newline="")
l=[]
r=csv.reader(f)
for i in r:
l.append(i)
for j in l:
if j==l[0]:
continue
else:
if int(j[-1])>65:
print(j)
f.close()
Q16 :write a menu driven program to implement stack operation using a list.
st=[]
while(1):
print ("1. PUSH")
print ("2. POP ")
print ("3. Display")
print("4.Exit")
choice=int(input("Enter your choice: "))
if (choice==1):
a=int(input("Enter any number :"))
st.append(a)
elif (choice==2):
if (st==[]):
print ("Stack Empty" )
else:
print ("Deleted element is : ",st.pop())
elif (choice==3):
length=len(st)
for i in range(length-1,-1,-1):
print (st[i])
elif (choice ==4):
break
else:
print("Invalid Input")
output:
1.PUSH
2.POP
3.Display
4.Exit
Enter your choice: 1
Enter any number:25
1.PUSH
2.POP
3.Display
4.Exit
Enter your choice: 1
Enter any number:10
1.PUSH
2.POP
3.Display
4.Exit
Enter your choice: 2
Deleted elements is :10
1.PUSH
2.POP
3.Display
4.Exit
Enter your choice: 3
25
1.PUSH
2.POP
3.Display
4.Exit
Enter your choice: 4
P17: Program to connect with database and store record of employee and
display records.
OUTPUT
0. ADD RECORD
1. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :1
Enter Name :AMIT
Enter Department :SALES
Enter Salary :9000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :1
Enter Employee Number :2
Enter Name :NITIN
Enter Department :IT
Enter Salary :80000
## Data Saved ##
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :2
EMPNO NAME DEPARTMENT SALARY
1 AMIT SALES 9000
2 NITIN IT 80000
1. ADD RECORD
2. DISPLAY RECORD
0. EXIT
Enter Choice :0
## Bye!! ##
OUTPUT