0% found this document useful (0 votes)
59 views99 pages

CS Practical File 12th (FINAL) - Tanisha Pahwa

Uploaded by

fulluniv
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)
59 views99 pages

CS Practical File 12th (FINAL) - Tanisha Pahwa

Uploaded by

fulluniv
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/ 99

/

MAXFORT SCHOOL ROHINI


PRACTICAL FILE
SUBJECT: COMPUTER SCIENCE
CLASS: XII
SESSION: 2023-24

SUBMITTED BY: SUBMITTED TO:

LAKSHYA AGARWAL Ms. PINKY GUPTA

CBSE ROLL NO.: HOD (Computer Science)


ACKNOWLEDGEMENT

I wish to express my deep sense of gratitude to the luminaryPrincipal, Dr. Ratna

Chakravarty, Maxfort School Rohini who has been continuously motivating us.

She provided us with invaluable advice and helped us in difficult periods. Her

motivation and help contributed tremendously to the successful completion of this

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

problem, occurred during its implementation.

LAKSHYA AGARWAL
CERTIFICATE

This is to certify that student LAKSHYA AGARWAL

CBSE Roll No.: has successfully completed the


practical file in the subject “Computer Science” laid down under the guidelines of
CBSE for the purpose of Practical Examination in Class XII, session: 2023-24

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

4. Write a Program to Calculate the Number of Words and the Number of


Characters Present in a String.

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.

str1=input("Enter first string:")


str2=input("Enter second string:")
count1=0
count2=0
for i in str1:
count1+=1
for i in str2:
count2+=1
if count1>count2:
print('"',str1,'"', 'is the larger string')
elif count2>count1:
print('"',str2,'"', 'is the larger string')
else:
print("Both strings are of equal length")

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:

7. Write a Program to Check if a String is a Palindrome or Not.

str = input ("Enter the string:")


l = len (str)
p = l-1
index = 0
while (index < p) :
if (str[index]==str[p]):
index = index + 1
p = p-1
else :
print ("String is not a palindrome")
break
else :
print("String is a palindrome")

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:

11. Write a Program to Check if a Substring is Present in a Given String.

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:

12. Write a Python Program to check First Occurrence of a Character in a


String.

str=input("Enter string:")
char=input("Enter character:")
index=str.find(char)
print(char, "is present at", index, "index position")

OUTPUT:

13. Write a Python Program to Remove Last Occurrence of a Character in a


String.

str=input("Enter String : ")


char=input("Enter Character to remove: ")
str2=''
l=len(str)
for i in range(l):
if(str[i]==char):
str2=str[0:i]+str[i+1:l]
print("Original String :", str)
print("Final String :", str2)
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]

list1 = [5, 10, 15, 20, 25, 50, 20]


index=list1.index(20)
print("Original list:", list1)
print("20 is present at", index, "index position")
list1[index]=200
print("Updated list:", list1)

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:

17.Write a function to convert the temperature from Fahrenheit to Celsius.

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.

print('#TO READ A SPECIFIC NUMBER OF BYTES:')


fin=open("Book.txt", 'r', encoding='utf-8')
n=int(input("Enter number of bytes you want to read:"))
str=fin.read(n)
print(str)
fin.close()
OUTPUT:

20.Write a Program to read the first line of the file ‘Book.txt’.

print('#TO READ THE FIRST LINE OF A FILE.')


fin=open("Book.txt", 'r', encoding='utf-8')
str=fin.readline()
print(str)
fin.close()
OUTPUT:

21.Write a program to read all the lines of the file ‘Book.txt’.

print('#TO READ ALL THE LINES OF A FILE')


fin=open("Book.txt", 'r', encoding='utf-8')
str=fin.readlines()
print(str)
fin.close()

OUTPUT

22.Write a program to count the number of characters from a text file, without
counting white spaces.

print("#TO COUNT NUMBER OF CHARACTERS FROM A FILE W/O


COUNTING WHITE SPACES")
fin=open("Book.txt",'r')
str=fin.read()
L=str.split()
print(L)
count=0
for i in L:
count=count+len(i)
print('Number of characters without counting spaces:',count)
fin.close()
OUTPUT

23.Write a program to count the number of characters with spaces.

print("#TO COUNT NUMBER OF CHARACTERS FROM A FILE WITH


COUNTING WHITE SPACES")
fin=open("Book.txt",'r')
str=fin.read()
count=0
for i in str:
count+=1
print('Number of characters with counting spaces:',count)
fin.close()

OUTPUT

24.Write a program to count the number of words in a file.

print("#TO COUNT NUMBER OF WORDS IN A FILE")


fin=open("Book.txt",'r')
str=fin.read()
L=str.split()
count_words=0
for i in L:
count_words+=1
print("Number of words in the file=:", count_words)
fin.close()

OUTPUT

25.Write a program to count the number of lines in a text file.

print("#TO COUNT NUMBER OF LINES IN A FILE ")


fin=open("Book.txt",'r')
str=fin.readlines()
count_lines=0
for i in str:
count_lines+=1
print("Number of lines in the file=",count_lines)
fin.close()

OUTPUT:

26.Write a program to count the number of vowels in a text file.

print("#TO COUNT NUMBER OF VOWELS IN A TEXT FILE ")


fin=open("Book.txt",'r')
str=fin.read()
count=0
for i in str:
if i in ['a','A','e','E','i','I','o','O','u','U']:
count+=1
print("Number of vowels in the file=",count)
fin.close()

OUTPUT:

27.Write a program to count number of 'is' word in a text file.

print("#TO COUNT NUMBER OF 'is' WORD IN A TEXT FILE ")


fin=open("Book.txt",'r')
str=fin.read()
print(str)
L=str.split()
count=0
for i in L:
if i=='is':
count+=1
print("Number of 'is' words in the file=",count)
fin.close()

OUTPUT:
28. Write a program to take the details of books from the user and write the
record in text file.

print("#TO TAKE DETAILS OF BOOK FROM USER AND RECORD IN A


TEXT FILE")
fout=open("BOOK_user.txt",'w')
n=int(input("How many records you want to write in a file ? :"))
for i in range(n):
print("Enter details of record", i+1)
title=input("Enter the title of book : ")
price=float(input("Enter price of the book: "))
record=title+" , "+str(price)+'\n'
fout.write(record)
fout.close( )

OUTPUT:

TEXT FILE:
29.Write a program to store the dictionary structure in Binary file format.

print("# TO STORE DICTIONARY STRUCTURE IN BINARY FILEFORMAT")


import pickle
myfile=open("project_file.txt",'wb')
dict1={'ename':'Jitendra', 'pname':'Simulator','Charge':45000}
pickle.dump(dict1,myfile)
myfile.close()

BINARY FILE:

30. Write a program to read and write data in a binary file.

print("# TO READ AND WRITE DATA IN BINARY FILE")


import pickle
mf=open("project_file.txt","wb")
dict1={1:"a",2:"b", 3:"c"}
pickle.dump(dict1,mf)
mf.close()
mf=open("project_file.txt",'rb')
dict1=pickle.load(mf)
print(dict1)
print("Item 1 is", dict1[1])
mf.close()

OUTPUT:

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.

print("#STORE DATA OF EMPLOYEES IN A BINARY FILE AND READ


PARTICULAR SALARIES")
import pickle
e={'Namita':25000,'Manya':30000,'Tanu':20000}
f1=open('emp.dat','wb')
pickle.dump(e,f1)
f1.close()
import pickle
f1=open('emp.dat','rb')
e=pickle.load(f1)
print("Employees having salary between 25000 to 30000")
for x in e:
if(e[x]>=25000 and e[x]<=30000):
print(x)
f1.close()

OUTPUT:

32.Write a program to store employee details in a binary file.

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.

print("#TO DISPLAY RECORD OF EMPLOYEES STORED IN THE BINARY


FILE")
import pickle
emp=[]
f=open("employee.txt",'rb')
ans='y'
while True:
try:
emp=pickle.load(f)
except EOFError:
break
print("%10s"%"EMP NO.","%20s"%"EMP NAME","%10s"%"EMP SALARY")
print("******************************************************")
for e in emp:
print("%10s"%e[0],'%20s'%e[1],"%10s"%e[2])
f.close()

OUTPUT:
/
34.Write a program to search record of employees in the binary file.

print("#TO SEARCH RECORD OF EMPLOYEES IN A BINARY FILE")


import pickle
emp=[]
f=open('employee.txt','rb')
ans='y'
print("****************** EMPLOYEE SEARCH FORM
************************************")
en=int(input("Enter Employee Number to search:"))
found=False
while True:
try:
emp=pickle.load(f)
except EOFError:
break
print("%10s"%"EMP NO.","%20s"%"EMP NAME","%10s"%"EMP SALARY")
print("******************************************************")
for e in emp:
if(e[0]==en):
print("%10s"%e[0],'%20s'%e[1],"%10s"%e[2])
found=True
break
if found==False:
print("## SORRY EMPLOYEE NUMBER NOT FOUND ##")
f.close()
OUTPUT:
35. Write a program to count the total number of records in binary file.

print("#TO COUNT THE TOTAL NUMBER OF RECORDS IN BINARY FILE")


import pickle
emp=[]
f=open('employee.txt','rb')
emp=pickle.load(f)
l=len(emp)
while True:
try:
emp=pickle.load(f)
except EOFError:
break
print("%10s"%"EMP NO.","%20s"%"EMP NAME","%10s"%"EMP SALARY")
print("******************************************************")
for e in emp:
print("%10s"%e[0],'%20s'%e[1],"%10s"%e[2])
print("******************************************************")
print("Total Records are :",l)

OUTPUT:
36. Write a program to update employee records in the binary file.

print("#TO UPDATE EMPLOYEE RECORDS IN THE BINARY FILE")


import pickle
emp=[]
f=open('employee.txt','rb')
emp=pickle.load(f)
print("## EMPLOYEE RECORDS ##")
print(emp)
print('-----------------------------------------')
f.close()

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.

print("#TO DELETE EMPLOYEE RECORDS IN THE BINARY")


import pickle
emp=[]
f=open('employee.txt','rb')
emp=pickle.load(f)
print("## EMPLOYEE RECORDS ##")
print(emp)
print('-----------------------------------------')
f.close()

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”

print("#TO CREATE BINARY FILE FIRST")


import pickle
emp=[]
f=open('Book.dat','wb')
ans='y'
while ans=='y':
Bookno=int(input("Enter Book number:"))
Book_Name=input("Enter Book Name:")
Author=input("Enter Author's name:")
Price=int(input("Enter Book Price:"))
emp.append([Bookno, Book_Name,Author])
ans=input("Add more records?")
pickle.dump(emp,f)
f.close()
#OUTPUT:

i.) import pickle

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:

ii.) import pickle


def countrec(Author):
fobj=open("Book.dat", "rb")
num = 0
while True:
try:
rec=pickle.load(fobj)
if Author==rec[2]:
num = num + 1
print(rec[0],rec[1],rec[2],rec[3])
except EOFError:
break
return num
n=countrec("Amit")
print("Total records", n)

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

ii. def A_E():


with open("NEWS.txt",'r') as f:
file=f.read()
for i in file:
if i.lower()=='a':
print("E",end='')
else:
print(i, end='')
A_E()

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

1. Write a program for traversing a list.

L=[10,20,30,40,50]
for i in range(len(L)):
print(L[i])

OUTPUT:

2. Write a program for searching an element in a list.

L=eval(input("Enter the elements: "))


n=len(L)
item=eval(input("Enter the element that you want to search : "))
for i in range(n):
if L[i]==item:
print("Element found at the position :", i+1)
break
else:
print("Element not Found")

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:

4. Write a menu driven program to implement stack functions.

#write a menu driven proram to implement stack functions.


S=[]
from os import system
def menu(): #menu display
ch=0
while(ch<1 or ch>4):
print ("\n")
print ("\t1: PUSH")
print ("\t2: POP")
print ("\t3: DISPLAY")
print ("\t4: EXIT")
ch=int(input("\n\tEnter a choice (1-4):"))
return ch

def push(): #code to push an item


item=int(input("\tEnter an item to push: "))
S.append(item)
print ("\tITEM" , item ," PUSHED IN THE STACK")
def pop(): #code to pop from stack
if (S==[]):
print ("\tNO ITEM TO POP")
else:
item=S.pop()
print ("\tITEM" , item ," POPPED FROM THE STACK")

def display(): #code to display stack


if (S==[]):
print ("\tEMPTY STACK")
else:
print ("\t",)
for i in S:
print( i ,' ',end="")

import sys #code to call all functions


ch=0
while(ch!=4):
ch=menu()
if(ch==1):
push()
elif(ch==2):
pop()
elif(ch==3):
display()
elif(ch==4):
print ("\tABORTING PROGRAM.....")
sys.exit()
anyvar=input("\n\tPress any key to continue...\n")

OUTPUT:
SQL QUERIES
Question 1:
Consider the following table named TEACHER and answer the following
questions based on it.

1. Create the above given table.


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.

4. Calculate the total salary given department wise.


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.

13. Display the total number of records in the table.


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.

16.Display the number of years every teacher has worked.


17. Display the count of teachers in every department.



18. Display the name of teachers who have joined in the month of January,
April and July

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.

Creating Tables first:


Table 1:

Table 2:

1. To display the details of those clients whose city is “Delhi”


2. To display the details of products whose price is in the range of 50 to 100.



3. To display the client name, city from table client and product name and price
from the table product with their corresponding matching P_ID.

4. To increase the price of the product by 10.


5. Write the output of the query:


Select distinct city from client;

Question 3:
Consider the following tables CONSIGNOR and CONSIGNEE. Answer
the questions given below.

TABLE: CONSIGNOR
Creating Tables first:
Table 1:
Table 2:

1. To display the names of all the consignors from Mumbai.


2. To display the cneeid, cnorname, cnoradress, cneename, cneeaddress for


every consignee.

3. To display consignee details in ascending order of cneename.

4. To display number of Consignee from each city


5. Write the output of the query: Select distinct cneecity from consignee;

Question4:
Consider the following tables and answer the questions given below.

Creating tables first:


Table 1:
Table 2:

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;

b.) SELECT MAX(M_Mf_Date), MIN(M_Mf_Date) FROM MobileMaster;


c.) SELECT M1.M_Id, M1.M_Name, M2.M_Qty, M2.M_Supplier FROM


MobileMaster M1, MobileStock M2 WHERE M1.M_Id=M2.M_Id AND
M2.M_Qty>=300;

d.) SELECT AVG(M_Price) FROM MobileMaster;


Question5:
Consider the following tables and answer the questions given below.

Creating tables first:


Table 1:
Table 2:

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.

4. To display number of Trainers from each city.


5. Find Output of following queries


a) SELECT TID, TNAME FROM TRAINER WHERE CITY NOT
IN(‘DELHI’, ‘MUMBAI’);

b) SELECT DISTINCT TID FROM COURSE;


c) SELECT TID, COUNT(*), MIN(FEES) FROM COURSE GROUP BY TID


HAVING COUNT(*)>1;

d) SELECT COUNT(*), SUM(FEES) FROM COURSE WHERE


STARTDATE< ‘2018-09-15’;

Question6:
Consider the following tables and answer the questions given below.
Creating tables first:
Table 1:

Table 2:

1. To display details of those Faculties whose salary is greater than 12000.



2. To display the details of courses whose fees is in the range of 15000 to
50000 (both values included).

3. To increase the fees of all courses by 500 of “System Design” Course.


4. To display details of those courses which are taught by ‘Sulekha’ in


descending order of courses.

5. Find output of following:


a) Select COUNT(DISTINCT F_ID) from COURSES;

b) Select MIN(Salary) from FACULTY,COURSES where COURSES.F_ID =
FACULTY.F_ID;

c) Select sum(fees) from COURSES where F_ID = 102;


d) Select avg(fees) from COURSES;


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.

3. To display total quantity in store of Unisex type watches.


4. To display watch name and their quantity sold in first quarter.


5. select max(price), min(qty_store) from watches;

6. select quarter, sum(qty_sold) from sale group by quarter;


7. select watch_name, qty_store, sum(qty_sold), qty_store-sum(qty_sold)


“Stock” from watches w, sale s where w.watchid=s.watchid group by
s.watchid;

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.

3. To increase marks of all students by 20 whose class is “XII”.


3.Find output of the following queries.


a) SELECT COUNT(*), City FROM STUDENT GROUP BY CITY HAVING
COUNT(*)>1;

b) SELECT MAX(DOB),MIN(DOB) FROM STUDENT;



c) SELECT NAME, GENDER FROM STUDENT WHERE CITY=’Delhi’;

PROGRAMS ON
PYTHON-SQL
CONNECTIVITY
1. Write a program to create a cursor object and use it.

import mysql.connector as _101


mydb=_101.connect(host='localhost', user='root', passwd='2021CORONA')
mycursor=mydb.cursor()
mycursor.execute('show databases')
for i in mycursor:
print (i)

OUTPUT:

2. Consider the following tables EMPLOYEE and SALGRADE.


Writecomplete 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
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")

ii) CREATE TABLE EMPLOYEE, SET ECODE AS PRIMARY KEY


AND INSERT RECORDS

import mysql.connector as mycon


mydb=mycon.connect(host='localhost', user='root', passwd='2021CORONA',
database='COMPANY')
mycursor=mydb.cursor()
mycursor.execute("Create table EMPLOYEE (ecode int(5)primary key,name
char(50),design char(50),sgrade varchar(5),DOJ varchar(40),DOB varchar(40))")
records=("INSERT INTO EMPLOYEE(ecode,name,design,sgrade,DOJ,DOB)
VALUES(%s,%s,%s,%s,%s,%s)")

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:

iii) CREATE TABLE SALGRADE, SET SGRADE AS PRIMARY KEY


AND INSERT RECORDS

import mysql.connector as mycon


mydb=mycon.connect(host='localhost', user='root', passwd='2021CORONA',
database='COMPANY')
mycursor=mydb.cursor()
mycursor.execute("create table SALGRADE(SGRADE varchar(3) primary key,
SALARY int(10),HRA int(10))")
records="INSERT INTO SALGRADE(sgrade,salary,hra) VALUES(%s,%s,%s)"

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:

iv) TO DISPLAY NAME AND DESIGN OF THOSE EMPLOYEES, WHOSE


SAL-GRADE IS EITHER S02 OR S03.

import mysql.connector as mycon


mydb=mycon.connect(host='localhost', user='root', passwd='2021CORONA',
database='COMPANY')
mycursor=mydb.cursor()
mycursor.execute("SELECT name, design FROM employee WHERE sgrade='S02'
OR sgrade='S03' ")
for x in mycursor:
print(x)

OUTPUT:

v) CREATE A NEW COLUMN NAMED AS CONTACTNO. IN


EMPLOYEE TABLE AND ADD RELEVANT RECORDS IN THAT
COLUMN FOR EACH EMPLOYEE.

import mysql.connector as mycon


mydb=mycon.connect(host='localhost', user='root', passwd='2021CORONA',
database='COMPANY')
mycursor=mydb.cursor()
mycursor.execute("ALTER TABLE EMPLOYEE ADD COLUMN
CONTACT_NUMBER char(10)")
mycursor.execute("UPDATE EMPLOYEE SET
CONTACT_NUMBER=7194490677 WHERE ECODE=101")
mycursor.execute("UPDATE EMPLOYEE SET
CONTACT_NUMBER=9090711863 WHERE ECODE=102")
mycursor.execute("UPDATE EMPLOYEE SET
CONTACT_NUMBER=9851444162 WHERE ECODE=103")
mycursor.execute("UPDATE EMPLOYEE SET
CONTACT_NUMBER=7856071639 WHERE ECODE=105")
mycursor.execute("UPDATE EMPLOYEE SET
CONTACT_NUMBER=7829935582 WHERE ECODE=108")
mydb.commit()
mycursor.execute("select * from employee")
for i in mycursor:
print(i)
OUTPUT:

vi)DELETE RECORDS OF ALL THOSE EMPLOYEES WHO ARE NOT


EXECUTIVES.

import mysql.connector as mycon


mydb=mycon.connect(host='localhost', user='root', passwd='2021CORONA',
database='COMPANY')
mycursor=mydb.cursor()
mycursor.execute("DELETE FROM EMPLOYEE WHERE DESIGN !=
'EXECUTIVE'")
mycursor.execute("select * from employee")
for i in mycursor:
print(i)

OUTPUT:
vii) UPDATE SALARY OF EACH EMPLOYEE BY INCREMENTING 10%.

import mysql.connector as mycon


mydb=mycon.connect(host='localhost', user='root', passwd='2021CORONA',
database='COMPANY')
mycursor=mydb.cursor()
mycursor.execute("UPDATE SALGRADE SET
SALARY=SALARY+(0.1*SALARY)")
mycursor.execute("select * from SALGRADE")
for i in mycursor:
print(i)

OUTPUT:

You might also like