You are on page 1of 66

ANDHRA

EDUCATION SOCIETY
DR.K.R.B.M SENIOR
SECONDARY SCHOOL
SEC-7 PUSHP VIHAR, DELHI-
110017

COMPUTER SCIENCE
PRACTICAL FILE
2021 - 2022
Submitted To: - Submitted By:-
Mrs.Neelam Ma’am Kamarushi Rachit Kumar
(PGT CS) Roll No: -
XIIth Science

INDEX
Program Program Description Remarks
No.
Term I Practicals
1. WAP TO INPUT THREE NO’S. AND DISPLAY
THE LARGEST AND SMALLEST NO.
2. WAP TO DETERMINE WHETHER THE NO. IS
A PERFECT NO., ARMSTRONG NO. OR A
PALINDROM
3. WAP TO INPUT A NO. AND CHECK IF THE
NO. IS A PRIME OR COMPOSITE NO.
4. WAP TO DISPLAY THE TERMS OF A
FIBONACCI SERIES
5. WAP TO COMPUTE THE GREATEST
COMMON DIVISOR (GCD) AND LEAST
COMMON MULTIPLE OF 2 INTEGERS.
6. WAP TO COUNT AND DISPLAY THE NO. OF
VOWELS,CONSONANTS,UPPERCASE,
LOWERCASE CHARACTERS IN A STRING
7. WAP TO FIND THE LARGEST NO. IN A LIST
8. WAP TO INPUT A LIST OF NUMBERS AND
SWAP ELEMENTS AT THE EVEN LOCATION
WITH THE ELEMENTS AT ODD LOCATION
9. WAP TO INPUT A TUPLE OF ELEMENTS AND
SEARCH FOR THE GIVEN ELEMENT IN THE
TUPLE
10. WAP TO CREATE A DICTIONARY WITH THE
ROLL NO.,NAME AND MARKS OF ‘N’
STUDENTS OF CLASS AND DISPLAY THE
NAME OF STUDENTS WHO SCORED ABOVE
75
11. WAP TO READ A TEXT FILE LINE BY LINE
AND DISPLAY EACH WORD SEPARATED BY #
12. WAP TO READ A TEXT FILE AND DISPLAY
THE NO. OF VOWELS,CONSONANTS,
UPPERCASE,LOWERCASE CHARACTERS IN
THE FILE
13. WAP TO REMOVE ALL THE LINES THAT
CONTAIN THE CHARACTER ‘A’ AND WRITE
IT TO ANOTHER FILE
14. WAP TO CREATE A BINARY FILE WITH NAME
AND ROLL NO. SEARCH FOR A GIVEN ROLL
NO. AND DISPLAY THE NAME,IF NOT
FOUND DISPLAY APPROPRIATE MESSAGE
15. WAP TO CREATE A BINARY FILE WITH ROLL
NO., NAME AND MARKS.INPUT THE ROLL
NO. AND UPDATE THE MARKS
16. WAP FOR A RANDOM NO. GENERATOR
THAT GENERATES RANDOM NO. BETWEEN
1 AND 6 (SIMULATES A DICE)
17. CREATE A CSV FILE BY ENTERING USER ID
AND PASSWORD. READ AND SEARCH THE
PASSWORD FOR A GIVEN USER ID
Term II Practicals
1. WAQ to create a database
2. WAQ to create a student table with
the student id, class, section, gender,
name, dob, and marks as
attributes where the student id is the
primary key.
3. WAQ to insert the details of at least 10
students in the above table.
4. WAQ to delete the details of a
particular student in the above table.
5. WAQ to increase marks by 5% for
those students who have Rno more
than 20.
6. WAQ to display the entire content of
the table.
7. WAQ to display Rno, Name and Marks
of those students who are scoring
marks more than 50.
8. WAQ to find the average of marks
from the student table.
9. WAQ to find the number of students,
who are from section 'A'.
10. WAQ to add a new column email in the
above table with appropriate data
type.
11. WAQ to add the email ids of each
student in the previously created email
column.
12. WAQ to display the information of all
the students, whose name starts with
'AN' (Examples: ANAND,
ANGAD,..)
13. WAQ to display Rno, Name, DOB of
those students who are born between
2005-01-01' and
2005-12-31'.
14. WAQ to display Rno, Name, DOB,
Marks, Email of those male students in
ascending order of their
names.
15. WAQ to display Rno, Gender, Name,
DOB, Marks, Email in descending order
of their marks.
16. WAQ to display the unique section
available in the table.
17. WAQ to add a new column, Mobile_no
of type integer in the table student
18. WAQ to Modify/Change the data type
size for the Name field from 20 to 25
characters
19. WAQ to Add a new column, Adm_no
of type integer and add a primary key
constraint in this column
20. WAQ to change the marks to 90 of a
student having Rollno is 9
21. WAQ to show all the male students
details
22. WAQ to show the distinct values of
stream
23. WAQ to list the details of all the
student who have secured more than
80 marks of are male
24. WAQ to display the records of all the
students who are not from commerce
section
25. WAQ to display Rollno,Name along
with marks of those students whose
marks lie in the range of 80 to 100
26. WAQ to display Rollno of those
students whose marks do not lie in the
range of 80 to 100
27. WAQ to display name of those
students whose stream is either
science or commerce.
28. WAQ to display Rollno,Name for those
students whose name ends with the
letter ‘a’
29. WAQ to display the average marks of
students
30. WAQ to display the total unique values
of marks in the table.
31. WAQ to display the name ,stream,
marks and count the total no. of
students who have scored more than
90 marks according to their stream
32. Write code to connect to a MySQL
database namely practical and then
fetch all those records from table
student where class is 11.
33. AES School is managing student data in
‘student’ table in practical database.
Write a Python code that connects to
database practical and retrieves all
records and display total number of
students.
34. ABC Infotech Pvt. Ltd. Needs to
store,retrieve and delete the records
of its employee. Develop an interface
that provides front end interaction
through Python , and stores and
updates records using MySQL. The
operations on MySQL table “emp”
involve reading, searching, updating
and deleting the records of employees.
a)Program to read and fetch all the
records from EMP table having salary
more than 70000.
b)Program to update the records of
employees by increasing salary by
1000 of all those employees who are
getting less than 80000
c)Program to delete the record on the
basis of inputted salary.
35. WAP to create a Stack called
Employee, to perform the basic
operations on Stack using list. The list
contains the two values-employee
number and employee name. The
program should include the options for
addition, deletion and display of
employee details.
Term I Practicals
PROGRAM 1
# WAP TO INPUT THREE NO’S. AND DISPLAY THE
LARGEST AND SMALLEST NO.
number1 = int(input('Enter First number : '))
number2 = int(input('Enter Second number : '))
number3 = int(input('Enter Third number : '))
def largest(num1, num2, num3):
if (num1 > num2) and (num1 > num3):
largest_num = num1
elif (num2 > num1) and (num2 > num3):
largest_num = num2
else:
largest_num = num3
print("The largest of the 3 numbers is : ", largest_num)
def smallest(num1, num2, num3):
if (num1 < num2) and (num1 < num3):
smallest_num = num1
elif (num2 < num1) and (num2 < num3):
smallest_num = num2
else:
smallest_num = num3
print("The smallest of the 3 numbers is : ",
smallest_num)
largest(number1, number2, number3)
smallest(number1, number2, number3)

OUTPUT
PROGRAM 2
#WAP TO DETERMINE WHETHER THE NO. IS A PERFECT
NO., ARMSTRONG NO. OR A PALINDROM
n = int(input("Enter any number: "))
#For Perfect Number
sum1 = 0
for i in range(1, n):
if(n % i == 0):
sum1 = sum1 + i
if (sum1 == n):
print("The number",n,"is a Perfect number!")
else:
print("The number",n,"is not a Perfect number!")
#For Armstrong Number
#calculated the length (number of digits)
order = len(str(n))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = n
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
# display the result
if n == sum:
print("The number",n,"is an Armstrong number")
else:
print("The number",n,"is not an Armstrong number")
#For Palindrome Number
k=n
temp=n
rev=0
while(k > 0):
dig=k%10
rev=rev*10+dig
k=k//10
if(temp==rev):
print("The number",n,"is a palindrome!")
else:
print("The number",n,"is not a palindrome!")

OUTPUT
PROGRAM 3
#WAP TO INPUT A NO. AND CHECK IF THE NO. IS A
PRIME OR COMPOSITE NO.
num = int(input("Enter any number : "))
if num > 1:
for i in range(2, num):
if (num % i) == 0:
print(num, "is a composite number")
break
else:
print(num, "is a Prime number")
elif num == 0 or 1:
print(num, "is a neither Prime NOR Composite
number")

OUTPUT
PROGRAM 4
# WAP TO DISPLAY THE TERMS OF A FIBONACCI SERIES
i = int(input("Enter the limit:"))
x=0
y=1
z=1
print("Fibonacci series\n")
print(x,y,end="")
while(z<=i) :
print(z, end='')
x=y
y=z
z =x+y

OUTPUT
PROGRAM 5
#WAP TO COMPUTE THE GREATEST COMMON DIVISOR
(GCD) AND LEAST COMMON MULTIPLE(LCM) OF 2
INTEGERS.
a,b = 24,18
c,d = a,b
gcd,lcm = 0,0
while b:
a,b = b,a%b
gcd = a
lcm = (c * d)/gcd
print ('GCD is ', gcd, '\nLCM is ',lcm)

OUTPUT
PROGRAM 6
#WAP TO COUNT AND DISPLAY THE NO. OF
VOWELS,CONSONANTS,UPPERCASE, LOWERCASE
CHARACTERS IN A STRING
string = input("Enter Your String : ")
vowels = consonants = uppercase = lowercase = 0
vowels_list = ['a','e','i','o','u']
for i in string:
if i in vowels_list:
vowels += 1
if i not in vowels_list:
consonants += 1
if i.isupper():
uppercase += 1
if i.islower():
lowercase += 1
print("Number of Vowels in this String = ", vowels)
print("Number of Consonants in this String = ", consonants)
print("Number of Uppercase characters in this String = ",
uppercase)
print("Number of Lowercase characters in this String = ",
lowercase)

OUTPUT

PROGRAM 7
#WAP TO FIND THE LARGEST NO. IN A LIST
def myMax(list1):
max = list1[0]
for x in list1:
if x > max :
max = x
return max
list1 = [10, 20, 4, 45, 99]
print("Largest element is:", myMax(list1))

OUTPUT

PROGRAM 8
#WAP TO INPUT A LIST OF NUMBERS AND SWAP
ELEMENTS AT THE EVEN LOCATION WITH THE
ELEMENTS AT ODD LOCATION
val = eval(input("Enter a list: "))
print( "Original List is:",val )
s = len(val)
if s%2! = 0:
s=s-1
for i in range(0,s,2):
val[i],val[i+1]=val[i+1],val[i]
print("List after swapping :",val)

OUTPUT

PROGRAM 9
#WAP TO INPUT A TUPLE OF ELEMENTS AND SEARCH
FOR THE GIVEN ELEMENT IN THE TUPLE
lst = [ ]
n = int(input("Enter number of elements : "))
for i in range(0, n):
ele = int(input("Enter elements:"))
lst.append(ele)
tupl=tuple(lst)
print("Tuple of elements inserted successfully")
def search(list,n):
for i in range(len(list)):
if list[i] == n:
return True
return False
a = input("Enter element to be found:")
if search(tupl, a):
print("Element Found")
else:
print("Element Not Found")
OUTPUT

PROGRAM 10
#WAP TO CREATE A DICTIONARY WITH THE ROLL
NO.,NAME AND MARKS OF ‘N’ STUDENTS OF CLASS
AND DISPLAY THE NAME OF STUDENTS WHO SCORED
ABOVE 75
result = { }
n = int(input("Enter number of students: "))
for i in range(n):
print("Enter Details of student No.", i+1)
rno = int(input("Roll No: "))
name = input("Name: ")
marks = int(input("Marks: "))
result[rno] = [name, marks]
print(result)
print('Names of students who have got marks more than 75:')
for student in result:
if result[student][1] > 75:
print(result[student][0])

OUTPUT
PROGRAM 11
#WAP TO READ A TEXT FILE LINE BY LINE AND DISPLAY
EACH WORD SEPARATED BY #
file=open("test.txt","r")
doc=file.readlines()
for i in doc:
words=i.split()
for a in words:
print(a+"#")
file.close()

OUTPUT

PROGRAM 12
#WAP TO READ A TEXT FILE AND DISPLAY THE NO. OF
VOWELS,CONSONANTS, UPPERCASE,LOWERCASE
CHARACTERS IN THE FILE
file = open("test.txt","r")
data = file.read()
print(data)
vowels = 0
consonants = 0
upper = 0
lower = 0
for ch in data:
if str.isupper(ch):
upper += 1
elif str.islower(ch):
lower += 1
ch = str.lower(ch)
if ch in "aeiou":
vowels += 1
elif ch in "bcdfghjklmnpqrstvwxyz":
consonants += 1
print("No. of Vowels : ",vowels)
print("No. of Consonants : ",consonants)
print("No. of Upper Case Letters are : ",upper)
print("No. of Lower Case Letters are : ",lower)

OUTPUT
PROGRAM 13
#WAP TO REMOVE ALL THE LINES THAT CONTAIN THE
CHARACTER ‘A’ AND WRITE IT TO ANOTHER FILE
fo=open("hp.txt","w")
fo.write("Harry Potter")
fo.write("There is a difference in all harry potter books\nWe
can see it as harry grows\nthe books were written by J.K
rowling ")
fo.close()
fo=open('hp.txt','r')
fi=open('writehp.txt','w')
l=fo.readlines()
for i in l:
if 'a' in i:
i=i.replace('a','')
fi.write(i)
fi.close()
fo.close()
OUTPUT
Contents of hp.txt file:

Contents of writehp.txt file:


PROGRAM 14
#WAP TO CREATE A BINARY FILE WITH NAME AND
ROLL NO. SEARCH FOR A GIVEN ROLL NO. AND DISPLAY
THE NAME,IF NOT FOUND DISPLAY APPROPRIATE
MESSAGE
import pickle
def insert(name,roll_no):
with open("reco.dat","ab") as file:
dic = {"Name":name, "Roll no.":roll_no}
pickle.dump(dic,file)
print("Saved!")
def Search(roll_no):
f = open("reco.dat","rb")
while True:
text = pickle.load(f)
try:
if text["Roll no."] == roll_no:
print("Search result:")
print("Roll no: ",text['Roll no.'])
print("Name: ",text['Name'])
break
except EOFError:
print("Roll no. not found!")
break
while True:
print("""\nMENU:
Press 1 to insert data.
Press 2 to search data.
Press 3 to quit.""")
inp = int(input())
if inp == 1:
while True:
name = input("\nEnter Name(type '!b' to go to
menu): ")
if name == "!B" or name == "!b":
break
else:
roll_no = int(input("Enter Roll No.: "))
insert(name,roll_no)
elif inp == 2:
while True:
roll_no = input("\nEnter Roll(type '!b' to go to
menu): ")
if roll_no == "!b" or roll_no == "!B":
break
else:
roll_no = int(roll_no)
Search(roll_no)
elif inp == 3:
break
else:
print("Invaild input\n")
OUTPUT
PROGRAM 15
#WAP TO CREATE A BINARY FILE WITH ROLL NO.,
NAME AND MARKS.INPUT THE ROLL NO. AND UPDATE
THE MARKS
import pickle
f=open("records.dat", "wb")
pickle.dump([1, "Ram", 90], f)
pickle.dump([2, "Ravi", 80], f)
pickle.dump([3, "Shyam", 90], f)
pickle.dump([4, "Priya", 80], f)
pickle.dump([5, "Anjali", 85], f)
f.close()
f=open("records.dat", "rb")
roll=int(input("Enter the Roll Number: "))
marks=float(input("Enter the updated marks: "))
List = [ ]
flag = False
while True:
try:
record=pickle.load(f)
List.append(record)
except EOFError:
break
f.close()
f=open("records.dat", "wb")
for rec in List:
if rec[0]==roll:
rec[2] = marks
pickle.dump(rec, f)
print("Record updated successfully")
flag = True
else:
pickle.dump(rec,f)
f.close()
if flag==False:
print("This roll number does not exist")
OUTPUT
PROGRAM 16
# WAP FOR A RANDOM NO. GENERATOR THAT
GENERATES RANDOM NO. BETWEEN 1 AND 6
(SIMULATES A DICE)
import random
def rolladice():
counter = 0
myList = [ ]
while (counter) < 6:
randomNumber = random.randint(1,6)
myList.append(randomNumber)
counter = counter + 1
if (counter)>= 6:
pass
else:
return myList
#Taking user input here
n=1
while (n==1):
n = int(input("Enter 1 to roll a dice and get a random
number:"))
print(rolladice())
break

OUTPUT
PROGRAM 17
# CREATE A CSV FILE BY ENTERING USER ID AND
PASSWORD. READ AND SEARCH THE PASSWORD FOR A
GIVEN USER ID
import csv
f=open('user.csv', 'r')
reader=csv.reader(f)
ID = input('Enter the User ID to search for: ')
for row in reader:
if (row[0]==ID):
print(row)

OUTPUT
Term II Practicals
PROGRAM 1
WAQ to create a database

PROGRAM 2
WAQ to create a student table with the student id,
class, section, gender, name, dob, and marks as
attributes where the student id is the primary key.
PROGRAM 3
WAQ to insert the details of at least 10 students in the
above table.
PROGRAM 4
WAQ to delete the details of a particular student in the
above table.

PROGRAM 5
WAQ to increase marks by 5% for those students who
have Rno more than 20.

PROGRAM 6
WAQ to display the entire content of the table.

PROGRAM 7
WAQ to display Rno, Name and Marks of those
students who are scoring marks more than 50.

PROGRAM 8
WAQ to find the average of marks from the student
table.

PROGRAM 9
WAQ to find the number of students, who are from
section 'A'.

PROGRAM 10
WAQ to add a new column email in the above table
with appropriate data type.

PROGRAM 11
WAQ to add the email ids of each student in the
previously created email column.
PROGRAM 12
WAQ to display the information of all the students,
whose name starts with 'AN'
PROGRAM 13
WAQ to display Rno, Name, DOB of those students
who are born between ‘2005-01-01’ and ‘2005-12-31’.

PROGRAM 14
WAQ to display Rno, Name, DOB, Marks, Email of
those male students in ascending order of their names.
PROGRAM 15
WAQ to display Rno, Gender, Name, DOB, Marks, Email
in descending order of their marks.

PROGRAM 16
WAQ to display the unique section available in the
table.
PROGRAM 17
WAQ to add a new column, Mobile_no of type integer
in the table student

PROGRAM 18
WAQ to Modify/Change the data type size for the
Name field from 20 to 25 characters
PROGRAM 19
WAQ to Add a new column, Adm_no of type integer
and add a primary key constraint in this column

PROGRAM 20
WAQ to change the marks to 90 of a student having
Rollno is 9
PROGRAM 21
WAQ to show all the male students details

PROGRAM 22
WAQ to show the distinct values of stream
PROGRAM 23
WAQ to list the details of all the student who have
secured more than 80 marks of are male

PROGRAM 24
WAQ to display the records of all the students who are
not from commerce section
PROGRAM 25
WAQ to display Rollno,Name along with marks of those
students whose marks lie in the range of 80 to 100

PROGRAM 26
WAQ to display Rollno of those students whose marks
do not lie in the range of 80 to 100
PROGRAM 27
WAQ to display name of those students whose stream
is either science or commerce.

PROGRAM 28
WAQ to display Rollno,Name for those students whose
name ends with the letter ‘a’
PROGRAM 29
WAQ to display the average marks of students

PROGRAM 30
WAQ to display the total unique values of marks in the
table.
PROGRAM 31
WAQ to display the name ,stream, marks and count
the total no. of students who have scored more than
90 marks according to their stream

PROGRAM 32
Write code to connect to a MySQL database namely
practical and then fetch all those records from table
student where class is 11.
import mysql.connector as a
db1 = a.connect(host="localhost",user="root",
passwd="root",database="practical")
mycursor=db1.cursor()
mycursor.execute("Select* from student where
Class=11")
myrecords = mycursor.fetchall()
for x in myrecords:
print(x)

OUTPUT

PROGRAM 33
AES School is managing student data in ‘student’ table
in practical database. Write a Python code that
connects to database practical and retrieves all records
and display total number of students.
import mysql.connector
db_connection = mysql.connector.connect(host="local
host",user="root",passwd="root",database="practical)
print("Mysql is connected successfully")
print(db_connection)
mycursor=db_connection.cursor()
mycursor.execute("Select* from student")
myrecords = mycursor.fetchall()
print("The records are as follows:-")
for x in myrecords:
print(x)
mycursor.execute("select count(*) from student ")
mycount = mycursor.fetchone()
print("The total no. of students are:-")
for x in mycount:
print(x)

OUTPUT

PROGRAM 34
ABC Infotech Pvt. Ltd. Needs to store,retrieve and delete the
records of its employee. Develop an interface that provides
front end interaction through Python , and stores and
updates records using MySQL. The operations on MySQL
table “emp” involve reading, searching, updating and
deleting the records of employees.
a)Program to read and fetch all the records from EMP table
having salary more than 70000.
b)Program to update the records of employees by increasing
salary by 1000 of all those employees who are getting less
than 80000
c)Program to delete the record on the basis of inputted
salary.

a) import mysql.connector
db1= mysql.connector.connect(host="localhost",user="root",
passwd="root",database="company")
cursor=db1.cursor()
sql = "select* from emp where salary > 70000;"
try:
cursor.execute(sql)
resultset = cursor.fetchall()
for x in resultset:
print(x)
except:
print("Error:unable to fetch data")
db1.close()

OUTPUT

b) import mysql.connector
db1= mysql.connector.connect(host="localhost",user="root",
passwd="root",database="company")
cursor=db1.cursor()
sql = "UPDATE EMP SET salary = salary +1000 WHERE
salary<80000;"
try:
cursor.execute(sql)
db1.commit()
except:
db1.rollback()
db1.close()

OUTPUT

c) import mysql.connector
db1= mysql.connector.connect(
host="localhost",
user="root",
passwd="root",database="company"
)
cursor=db1.cursor()
sal=int(input("Enter salary whose record is to be deleted: "))
sql = "DELETE FROM EMP WHERE salary < '%d';" %(sal)
try:
cursor.execute(sql)
print(cursor.rowcount,end=" record(s) deleted")
db1.commit()
except:
db1.rollback()
db1.close()

OUTPUT
PROGRAM 35
WAP to create a Stack called Employee, to perform the
basic operations on Stack using list. The list contains
the two values-employee number and employee name.
The program should include the options for addition,
deletion and display of employee details.
Employee = [ ]
c= "y"
while (c=="y"):
print("1. PUSH")
print("2. POP")
print("3. Display")
choice= int(input("Enter your choice: "))
if (choice==1):
e_id=input("Enter Employee no : ")
ename=input("Enter the employee
name :")
emp = (e_id,ename)
Employee.append(emp)
elif (choice==2):
if (Employee==[]):
print("Stack Empty")
else:
e_id,ename=Employee.pop()
print("Deleted element is : ",e_id,ename)
elif (choice==3):
i=len(Employee)
while i>0:
print(Employee[i-1])
i=i-1
else:
print("Wrong Input")
c=input("Do you want to continue or not?")
OUTPUT

You might also like