CS Practical File 12th (FINAL) - Tanisha Pahwa
CS Practical File 12th (FINAL) - Tanisha Pahwa
Chakravarty, Maxfort School Rohini who has been continuously motivating us.
She provided us with invaluable advice and helped us in difficult periods. Her
file work.
My sincere thanks to Ms. Pinky Gupta, teacher in-charge, a guide and a mentor
who critically reviewed my practical file and helped in solving each and every
LAKSHYA AGARWAL
CERTIFICATE
______________________
Signature of the Invigilator
______________________
Signature of the Examiner
______________________
Signature of the Principal
INDEX
INDEX
S.NO TOPIC TEACHER’S
SIGNATURE
1. Write a Program to Count the Number of Vowels
in a String.
2. Write a Program to Take in a String and Replace
Every Blank Space with Hyphen.
3. Write a Program to Calculate the Length of a
String Without Using a Library Function.
4. Write a Program to Calculate the Number of
Words and the Number of Characters Present in a
String.
5. Write a Program to Take in Two Strings and
Display the Larger String without Using Built-in
Functions.
6. Write a Program to Count Number of Lowercase
Characters in a String.
7. Write a Program to Check if a String is a
Palindrome or Not.
8. Write a Program to Calculate the Number of
Digits and Letters in a String.
9. Write a Program to Form a New String Made of
the First 2 and Last 2 characters From a Given
String.
10. Write a Program to Count the Occurrences of
Each Word in a Given String Sentence.
11. Write a Program to Check if a Substring is
Present in a Given String.
12./ Write a Python Program to check First
Occurrence of a Character in a String.
13. Write a Python Program to Remove Last
Occurrence of a Character in a String.
14. Given a Python list, find value 20 in the list, and
if it is present, replace it with 200. Only update
the first occurrence of a value.
15. Write a Python program to count the number of
strings where the string length is 2 or more and
the first and last character are same from a given
list of strings.
16. Write a function to find the sum of 2 integers/2
variables.
17. Write a function to convert the temperature from
Fahrenheit to Celsius.
18. Write a python function to find the two roots of
quadratic equation and return the values using
all the probabilities.
19. Consider a file ‘book.txt’ with some text. Read a
specified number of bytes.
20. Write a Program to read the first line of the file
‘Book.txt’
21. Write a program to read all the lines of the file
‘Book.txt’.
22. Write a program to count the number of
characters from a text file, without counting white
spaces.
23. Write a program to count the number of
characters with spaces.
24. Write a program to count the number of words in
a file.
25. Write a program to count the number of lines in a
text file.
26. Write a program to count the number of vowels in
a text file.
27. Write a program to count number of 'is' word in a
text file.
28. Write a program to take the details of books from
the user and write the record in text file.
29. Write a program to store the dictionary structure
in Binary file format.
30. Write a program to read and write data in a binary
file.
31. Write a program to store data of employees w/
names, their salaries, in a binary file format and
then read the data of only those employees, who
are having salary between 25000 & 30000.
32. Write a program to store the names of several
employees in a binary file.
33. Write a program to store employee details in a
binary file.
34. Write a program to display record of employees
stored in the binary file
35. Write a program to search record of employees in
the binary file.
36. Write a program to count the total number of
records in binary file.
37. Write a program to update employee records in
the binary file.
38. Write a program to delete employee records in the
binary file.
39.1. A binary file “Book.dat” has structure [BookNo,
Book_Name, Author, Price].
i. Write a user defined function CreateFile() to
input data for a record and add to Book.dat .
ii. Write a function CountRec(Author) in
Python which accepts the Author name as
parameter and count and return number of
books by the given Author are stored in the
binary file “Book.dat”
40. Write a python program using function in python
to read lines from file "POEM.txt" and display all
those words, which has two characters in it.
41. Write a python program using function dispS() in
Python to read from text file "POEM.TXT" and
display those lines which starts with "S".
42. Write a python program using function
COUNTSIZE() in Python to read the file
"POEM.TXT" and display size of file.
43. Write a python python program using function
ATOEDISP() for each requirement in Python to
read the file "NEWS.TXT" and
i. Display "E" in place of all the occurrence of
"A" in the word COMPUTER.
ii. Display "E" in place of all the occurrence of
"A"
1. Write a function to write data into binary file
marks.dat and display the records of students who
scored more than 95 marks.
2. Write a program to store customer data into a
binary file cust.dat using a dictionary and print
them on screen after reading them. The customer
data contains ID as key, and name, city as values.
BASIC PYTHON
PROGRAMS
1. Write a Program to Count the Number of Vowels in a String.
str1=input("Enter string:")
vowels=['a','e','i','o','u']
count=0
for i in str1:
if i in vowels:
count+=1
print("Total vowel occurs are:", count)
OUTPUT:
2. Write a Program to Take in a String and Replace Every Blank Space with
Hyphen.
str=input("Enter a string:")
str=str.replace(" ","-")
print("New string:", str)
OUTPUT:
3. Write a Program to Calculate the Length of a String Without Using a Library
Function.
string=input("Enter a string:")
count=0
for i in string:
count+=1
print("Length of string is=",count)
OUTPUT:
string=input("Enter a string:")
num=0
alpha=0
for i in string:
if i.isdigit():
num+=1
elifi.isalpha():
alpha+=1
print("The number of digits=", num)
print("The number of alphabets=", alpha)
OUTPUT:
5. Write a Program to Take in Two Strings and Display the Larger String
without Using Built-in Functions.
OUTPUT:
6. Write a Program to Count Number of Lowercase Characters in a String.
count=0
inputString= input("Enter string:")
for char in inputString:
if char.islower():
count+=1
print("Number of lowercase characters=", count)
OUTPUT:
OUTPUT:
8. Write a Program to Calculate the Number of Digits and Letters in a String.
d1=0
c1=0
string = input("Enter String:")
for char in string:
if char.islower() or char.isupper():
c1+=1
elif char.isnumeric():
d1+=1
print("Number of letters in the string=", c1)
print("Number of digits in the string= ", d1)
OUTPUT:
9. Write a Program to Form a New String Made of the First 2 and Last 2
characters From a Given String.
str=input("Enter string:")
if len(str)>=2:
count=0
for i in str:
count+=1
start=str[0:2]
last=str[count-2:count]
print(start+last)
else:
print("Enter a larger string")
OUTPUT:
10.Write a Program to Count the Occurrences of Each Word in a Given String
Sentence.
def word_count(str):
counts=dict()
words=str.split()
for word in words:
if word in counts:
counts[word]+= 1
else:
counts[word]=1
return counts
string=input("Enter string:")
print(word_count(string))
OUTPUT:
str=input("Enter string:")
substr=input("Enter substring:")
if substr in str:
print("The substring is present in the given string.")
else:
print("The substring is not present in the given the string.")
OUTPUT:
str=input("Enter string:")
char=input("Enter character:")
index=str.find(char)
print(char, "is present at", index, "index position")
OUTPUT:
14.Given a Python list, find value 20 in the list, and if it is present, replace it with
200. Only update the first occurrence of a value.
list1 = [5, 10, 15, 20, 25, 50, 20]
Expected output:
list1 = [5, 10, 15, 200, 25, 50, 20]
OUTPUT:
15. Write a Python program to count the number of strings where the string
length is 2 or more and the first and last character are same from a given list
of strings.
Sample List : ['abc', 'xyz', 'cbc', '121']
Expected Result : 2
lst=['Rad',"ABC",'CABC',"181","XYZ"]
countsame=0
for i in lst:
if i[0]==i[-1]:
countsame+=1
print(lst)
print(countsame)
OUTPUT:
PROGRAMS
ON
FUNCTIONS
16.Write a function to find the sum of 2 integers/2 variables.
def sum(x,y):
a=x+y
return(a)
a=int(input("Enter first number:"))
b=int(input("Enter second number:"))
s=sum(a,b)
print("Sum of the two numbers=",s)
OUTPUT:
def convert_temp():
F=int(input("Enter temperature in Fahrenheit:"))
C=5/9*(F-32)
return (C)
temp=convert_temp()
print("Temperature in Celsius=", temp,"C")
OUTPUT:
18.Write a python function to find the two roots of quadratic equation and
return the values using all the probabilities.
def roots():
a= float(input("Enter the coefficient of x^2:"))
b= float(input("Enter the coefficient of x:"))
c= float(input("Enter the constant value:"))
d=b**2-4*a*c
x=d**(1/2)
m=(-b-x)/(2*a)
n=(-b+x)/(2*a)
return(m,n)
r1,r2= roots()
print("Roots of the equation are:", r1,’,’r2)
OUTPUT:
PROGRAMS
ON FILE
HANDLING
19.Consider a file ‘book.txt’ with the following text:
“Python is interactive language. It is case sensitive language.
It makes the difference between uppercase and lowercase letters. It is official
language of google.”
Read a specified number of bytes.
OUTPUT
22.Write a program to count the number of characters from a text file, without
counting white spaces.
OUTPUT
OUTPUT
OUTPUT:
OUTPUT:
OUTPUT:
28. Write a program to take the details of books from the user and write the
record in text file.
OUTPUT:
TEXT FILE:
29.Write a program to store the dictionary structure in Binary file format.
BINARY FILE:
OUTPUT:
OUTPUT:
import pickle
emp=[]
f=open('employee.txt', 'wb')
ans='y'
while ans.lower()=='y':
eno=int(input("Enter Employee Number:"))
name=input("Enter Employee Name:")
salary=int(input("Enter Salary:"))
emp.append([eno,name,salary])
ans=input("Add more records?")
pickle.dump(emp,f)
f.close()
OUTPUT:
33.Write a program to display record of employees stored in the binary file.
OUTPUT:
/
34.Write a program to search record of employees in the binary file.
OUTPUT:
36. Write a program to update employee records in the binary file.
f=open('employee.txt','wb')
found=False
en=int(input("Enter Employee Number to update:"))
for i in range(len(emp)):
if emp[i][0]==en:
sl=int(input("Enter new Salary:"))
emp[i][2]=sl
found=True
print("## RECORD UPDATES ##")
if not found:
print("## NO SUCH EMPLOYEE NUMBER FOUND ##")
pickle.dump(emp,f)
f.close()
f=open('employee.txt','rb')
emp=pickle.load(f)
print("## EMPLOYEE RECORDS AFTER UPDATION ##")
print(emp)
print('-----------------------------------------')
OUTPUT:
37. Write a program to delete employee records in the binary file.
f=open('employee.txt','wb')
found=False
en=int(input("Enter Employee Number to Delete:"))
emp2=[]
for i in range(len(emp)):
if emp[i][0]!=en:
emp2.append(emp[i])
pickle.dump(emp2,f)
f.close()
f=open('employee.txt','rb')
emp=pickle.load(f)
print("## EMPLOYEE RECORDS AFTER DELETION ##")
print(emp)
print('-----------------------------------------')
OUTPUT:
38. A binary file “Book.dat” has structure [BookNo, Book_Name, Author, Price].
i. Write a user defined function CreateFile() to input data for a record and
add to Book.dat .
ii. Write a function CountRec(Author) in Python which accepts the Author
name as parameter and count and return number of books by the given
Author are stored in the binary file “Book.dat”
def createfile():
f=open('Book.dat','ab')
BookNo=int(input('Enter Book Number : '))
Book_name=input('Enter Book Name :')
Author = input('Enter Author name:')
Price = int(input('Price of book :'))
rec=[BookNo, Book_name ,Author, Price]
pickle.dump(rec, fobj)
f.close()
createfile()
OUTPUT:
OUTPUT:
39.Write a python program using function in python to read lines from file
"POEM1.txt" and display all those words, which has two characters in it.
def read_lines():
with open('poem1.txt','r') as f:
lines=f.read()
print(lines)
count=0
L=lines.split()
print("Words with two characters:")
for e in L:
if len(e)==2:
print(e)
count+=1
print("Total such words:",count)
read_lines()
OUTPUT:
40. Write a python program using function dispS() in Python to read from text
file "POEM1.TXT" and display those lines which starts with "S".
def dispS():
with open("POEM1.txt",'r') as f:
for i in f:
if i[0].lower()=="s":
print(i)
dispS()
TEXT FILE:
OUTPUT:
41. Write a python program using function COUNTSIZE() in Python to read the
file "POEM1.TXT" and display size of file.
def COUNTSIZE():
with open("poem1.txt",'r') as file:
L=file.read()/
print("Size of file is:",len(L))
COUNTSIZE()
OUTPUT:
42.Write a python python program using function A_E() for each requirement in
Python to read the file "NEWS.TXT" and
i. Display "E" in place of all the occurrence of "A" in the word
COMPUTER.
i. def A_E():
with open("NEWS.txt",'r') as f:
file=f.read()
L=file.split()
for words in L:
if 'computar' in words.lower():
words=words.replace("A","E")
print(words, end=' ')
A_E()
TEXT FILE:
OUTPUT:
ii. Display "E" in place of all the occurrence of "A":
TEXT FILE:
OUTPUT:
INDEX
S.NO TOPIC TEACHER’S
SIGNATURE
1.
1. Write a program for traversing a list.
2.
1. Write a program for searching an element in a list.
3. Write a program for linear search of an element.
4. Write a program for binary search of an element.
5. Write a menu driven program to implement stack
functions.
1. Consider the following table named TEACHER
and answer questions based on it.
2. Consider the following tables PRODUCT and
CLIENT. Answer the questions given.
3. Consider the following tables CONSIGNOR and
CONSIGNEE. Answer the questions given.
4. Consider the following tables MOBILEMASTER
and MOBILESTOCK. Answer the questions given.
5. Consider the following tables TRAINER and
COURSE. Answer the questions given.
6. Consider the following tables FACULTY and
COURSES. Answer the questions given.
7. Consider the following tables WATCHES and
SALE. Answer the questions given.
8. Consider the following table STUDENT and
answer the questions given.
9. Write a program to create a cursor object and use it
10. Consider the given tables EMPLOYEE and
SALGRADE. Write complete python programs for
the given below SQL queries:
Assume that the database name is company and
create these two tables.
Write python code fragments for the given SQL
commands:
i.) Create database
ii.) Create table employee, set ecode as primary
key and insert records
iii.) Create table salgrade, set sgrade as primary
key and insert records
iv.) To display name and design of those
employees, whose salgrade is either s02 or
s03.
v.) Create a new column named as contact no.
In employee table and add relevant records
in that column for each employee.
vi.) Delete records of all those employees who
are not executives.
vii.) Update salary of each employee by
incrementing 10%.
PROGRAMS
ON STACKS
AND LISTS
L=[10,20,30,40,50]
for i in range(len(L)):
print(L[i])
OUTPUT:
OUTPUT:
3. Write a program for linear search of an element.
def linear_Search(mylist,item):
n = len(mylist)
for i in range(n):
if item == mylist[i]:
return i
return None
A=[]
n = int(input("Enter how many items in List:"))
for i in range(n):
d = int(input("Enter value :"))
A.append(d)
key = int(input("Enter Value to Search :"))
pos = linear_Search(A,key)
if pos!=None:
print("Found at position ",pos+1)
else:
print("Not Found")
OUTPUT:
4.Write a program for binary search of an element.
def B_Search(mylist,item):
low=0
high=len(mylist)-1
while(low<=high):
mid=(low+high)//2
if mylist[mid]==item:
return mid
elif mylist[mid]>item:
high=mid-1
else:
low=mid+1
return( -1)
A=eval(input("Enter the elements in sorted order: "))
n=len(A)
key=int(input("Enter the element that you want to search :"))
pos=B_Search(A,key)
if pos==len(A):
print("Search Item Not Found")
else:
print("Item found at position:",pos+1)
OUTPUT:
OUTPUT:
SQL QUERIES
Question 1:
Consider the following table named TEACHER and answer the following
questions based on it.
2. Insert 5 records
3. List the names in capital of the male teachers who are in science or
commerce Department in the descending order of their salary.
5. Increase the salary of all those teachers who have joined before 10-May-
2019 by 20%
6. Display the average salary given for computer dept.
7. Display the department names where the total salary disbursed is more than
250000
8. Display the teacher name, age and salary rounded off to hundredth place.
9. Display the teacher name along with the length of each name.
10. Display those department names where the number of teacher’s working is
more than 5.
11. Display the position of the occurrence of ’a’ in all the teacher names.
12. Display the highest and lowest salary value for each department.
14. Display those department names where the maximum bonus given is more
than 12000.
15. Display a report showing the average bonus given to every department.
19. Display the count of male and female teachers in the school
20. Display the teacher name, day (name of day), month and year of joining for
all teachers in the descending order of salary
21. Display the teacher’s name along with their salary truncated to zero decimal
places.
22. Display the teacher number along with their names who have not yet been
given any department.
Question 2:
Consider the following tables product and client. Answer the questions given
Below.
Table 2:
TABLE: CONSIGNOR
Creating Tables first:
Table 1:
Table 2:
5. Write the output of the query: Select distinct cneecity from consignee;
Question4:
Consider the following tables and answer the questions given below.
1. Display the Mobile company, Mobile name & price in descending order of
their manufacturing date.
2. Display the Mobile supplier & quantity of all mobiles except “MB003”.
3. Find Output of following queries
a.) SELECT M_Id, SUM(M_Qty) FROM MobileStock GROUP BY M_Id;
Question5:
Consider the following tables and answer the questions given below.
1. Display the Trainer Name, City & Salary in descending order of their
Hiredate.
2. To display the TNAME and CITY of Trainer who joined the Institute in the
month of December 2001.
3. To display TNAME, HIREDATE, CNAME, STARTDATE from tables
TRAINER and COURSE of all those courses whose FEES is less than or
equal to 10000.
Question6:
Consider the following tables and answer the questions given below.
Creating tables first:
Table 1:
Table 2:
Question7:
Consider the following tables and answer the questions given below.
Creating tables first:
Table 1:
Table 2:
1. To display all the details of those watches whose name ends with ‘Time’.
2. To display watch’s name and price of those watches which have price range
in between 5000-15000.
Question8:
Consider the following tables and answer the questions given below.
Creating table first:
1. To display the records from table student in alphabetical order as per the
name of the student.
2. To display Class, Dob and City whose marks is between 450 and 551.
OUTPUT:
i) CREATE DATABASE
import mysql.connector as mycon
mydb=mycon.connect(host='localhost', user='root', passwd='2021CORONA')
mycursor=mydb.cursor()
mycursor.execute("CREATE DATABASE COMPANY")
mycursor.execute("USE COMPANY")
val=[
(101,'Abdul Ahmad','EXECUTIVE','S03',"23-Mar-2003","13-Jan-1980"),
(102,'Ravi Chandar','HEAD-IT','S02','12-Feb-2010','22-Jul-1987'),
(103,'John Ken','RECEPTIONIST','S03','24-Jun-2009','24-Feb-1983'),
(105,'Nazar Ameen','GM','S02','11-Aug-2006','03-Mar-1984'),
(108,'Priyam Sen','CEO','S01','29-Dec-2004','19-Jan-1982')]
mycursor.executemany(records,val)
mydb.commit()
mycursor.execute("Select * from Employee")
for i in mycursor:
print(i)
OUTPUT:
val=[
("S01",56000,18000),
("S02",32000,12000),
("S03",24000,8000)
]
mycursor.executemany(records,val)
mydb.commit()
mycursor.execute("select * from SALGRADE")
for i in mycursor:
print(i)
OUTPUT:
OUTPUT:
OUTPUT:
vii) UPDATE SALARY OF EACH EMPLOYEE BY INCREMENTING 10%.
OUTPUT: