[go: up one dir, main page]

0% found this document useful (0 votes)
53 views16 pages

Cs Practical New-Final

Uploaded by

FLASH Op YT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
53 views16 pages

Cs Practical New-Final

Uploaded by

FLASH Op YT
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Computer science practical [2023-2024]

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

num = int(input("Enter any number :"))


isPrime=True
for i in range(2,num):
if num % i == 0:
isPrime=False
break
if isPrime==True:
print("## Number is Prime ##")
else:
print("## Number is not Prime ##")
OUTPUT
Enter any number :20
## Number is not Prime ##
>>>
Enter any number :19
## Number is Prime ##

Q4:Write a program to find whether an inputted number is perfect 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

def Merge(dict1, dict2):


return(dict2.update(dict1))
dict1 = {'a': 10, 'b': 8}
dict2 = {'d': 6, 'c': 4}
print(Merge(dict1, dict2))
print(dict2)

Output:

None
{‘d’:6,'c': 4, 'a': 10, 'b': 8 }

==========================================================================
10: Write a python Program to add two matrices using nested loop.

X = [[1,2,3],[4 ,5,6],[7 ,8,9]]


Y = [[9,8,7], [6,5,4], [3,2,1]]
result = [[0,0,0], [0,0,0],[0,0,0]]
for i in range(len(X)):
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
for r in result:
print(r)

Output:

[10, 10, 10]


[10, 10, 10]
[10, 10, 10]

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

if the original content of file is:


India is my country
I love python
Python learning is fun
123@

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

## File Copied Successfully! ##

After copy content of file2copy.txt


one two three four five six seven
eight nine ten
bye!

==============================================================================
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

Enter Roll Number :1

Enter Name :Amit

Add More ?(Y)y


Enter Roll Number :2
Enter Name :Jasbir
Add More ?(Y)n

Enter Roll number to search :2


## Name is : Jasbir ##
Search more ?(Y) :y

Enter Roll number to search :4


####Sorry! Roll number not found ####
Search more ?(Y) :n
==============================================================================
Q14: Write a python Program to create binary file to store Rollno, Name and Marks
and update marks of entered Rollno.

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

Enter Roll Number :1

Enter Name :Amit

Enter Marks :99


Add More ?(Y)y
Enter Roll Number :2
Enter Name :Vikrant
Enter Marks :88
Add More ?(Y)n

Enter Roll number to update :2


Enter new marks :90
## Record Updated ##
Update more ?(Y) :y
Enter Roll number to update :2
Enter new marks :95
## Record Updated ##
Update more ?(Y) :n

==============================================================================
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.

import mysql.connector as mycon


con = mycon.connect(host='127.0.0.1',user='root',password="admin" database=”company”)
cur = con.cursor()
cur.execute("create table employee(empno int, name varchar(20), dept varchar(20),salary int)")
con.commit()
choice=None
while choice!=0:
print("1. ADD RECORD ")
print("2. DISPLAY RECORD ")
print("0. EXIT")
choice = int(input("Enter Choice :"))
if choice == 1:
e = int(input("Enter Employee Number :"))
n = input("Enter Name :")
d = input("Enter Department :")
s = int(input("Enter Salary :"))
query="insert into employee values({},'{}','{}',{})".format(e,n,d,s)
cur.execute(query)
con.commit()
print("## Data Saved ##")
elif
choice == 2:
query="select * from employee"
cur.execute(query)
result = cur.fetchall()
for row in result:
print(row[0],row[1],row[2],row[3])
elif choice==0:
con.close()
print("## Bye!! ##")
else:
print("## INVALID CHOICE ##")

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!! ##

P18: Program to connect with database and search employee number in


table employee and display record, if empno not found display appropriate
message.

import mysql.connector as mycon


con = mycon.connect(host='127.0.0.1',user='root',password="admin", database="company")
cur = con.cursor()
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
for row in result:
print(row[0], row[1], row[2], row[3])
ans=input("SEARCH MORE (Y) :")

OUTPUT

ENTER EMPNO TO SEARCH :1


1 AMIT SALES 9000
SEARCH MORE (Y) :y
ENTER EMPNO TO SEARCH :2
2 NITIN IT 80000
SEARCH MORE (Y) :y
ENTER EMPNO TO SEARCH :4
Sorry! Empno not found
SEARCH MORE (Y) :n
P19: Program to connect with database and update the employee record of
entered empno.
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin", database="company")
cur = con.cursor()
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO UPDATE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
for row in result:
print(row[0], row[1], row[2], row[3])
choice=input("\n## ARE YOUR SURE TO UPDATE ? (Y) :")
if choice.lower()=='y':
d = input("ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT
TO CHANGE )")
if d==" ":
d=row[2]
try:
s = int(input("ENTER NEW SALARY,(LEAVE BLANK IF NOT
WANT TO CHANGE ) "))
except:
s=row[3]
query="update employee set dept='{}',salary={} where empno={}".format
(d,s,eno)
cur.execute(query)
con.commit()
print("## RECORD UPDATED ## ")
ans=input("UPDATE MORE (Y) :")
OUTPUT

ENTER EMPNO TO UPDATE :2


2 NITIN IT 90000

## ARE YOUR SURE TO UPDATE ? (Y) :y


ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO
CHANGE )
ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE )
## RECORD
UPDATED ##
UPDATE MORE
(Y) :y

ENTER EMPNO TO UPDATE :2


2 NITIN IT 90000
## ARE YOUR SURE TO UPDATE ? (Y) :y
ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO CHANGE )
ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE )
## RECORD
UPDATED ##
UPDATE MORE
(Y) :Y

ENTER EMPNO TO UPDATE :2


2 NITIN SALES 90000

## ARE YOUR SURE TO UPDATE ? (Y) :Y


ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT WANT TO
CHANGE )
ENTER NEW SALARY,(LEAVE BLANK IF NOT WANT TO CHANGE )
91000
## RECORD UPDATED ##
UPDATE MORE (Y) :Y

ENTER EMPNO TO UPDATE :2


2 NITIN SALES 91000

## ARE YOUR SURE TO UPDATE ?


(Y) :
N UPDATE MORE (Y) :N

P20: Program to connect with database and delete the record of


entered employee number.
import mysql.connector as mycon
con = mycon.connect(host='127.0.0.1',user='root',password="admin", database="company")
cur = con.cursor()
ans='y'
while ans.lower()=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print(“Sorry! Empno not found “)
else:
for row in result:
print(row[0], row[1], %row[2], row[3])
choice=input("\n## ARE YOUR SURE TO DELETE ? (Y) :")
if choice.lower()=='y':
query="delete from employee where empno={}".format(eno)
cur.execute(query)
con.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")
OUTPUT
ENTER EMPNO TO DELETE :2
2 NITIN SALES 91000
## ARE YOUR SURE TO DELETE ? (Y) :y
=== RECORD DELETED SUCCESSFULLY! ===
DELETE MORE ? (Y) :y
ENTER EMPNO TO DELETE :2
Sorry! Empno not found
DELETE MORE ? (Y) :n

You might also like