You are on page 1of 45

SESSION: 2020 – 21

COMPUTER SCIENCE
PRACTICAL FILE
CLASS XII – C

Submitted To: Submitted By:


Mrs. Vandana Jindal Mahir Bhardwaj
CONTENT
➢ WAP to accept a string and whether it is a
palindrome or not.
➢ Write a program to show statistics of
characters in the given line (to counts the
number of alphabets, digits, uppercase,
lowercase).
➢ WAP to remove all odd numbers from the
given list.
➢ WAP to display frequencies of all the element
of a list.
➢ WAP to display those string which starts with
‘A’ from the given list.
➢ WAP to find and display the sum of all the
values which are ending with 3 from a list.
➢ Write a program to show sorting of elements of
a list step – by – step.
➢ A list num contains the following elements :
3,21,5,6,14,8,14,3 .WAP to swap the content
with next value, if it is divisible by 7 so that the
resultant array will look like :
3,5,21,6,8,14,3,14.
➢ Write a program to accept values from a user
and create a tuple.
CONTENT
➢ WAP to input total number of sections and
stream name in 11th class and display all
information on the output screen.
➢ Write a Program using python to find the
Occurrence of any word in a string.
➢ Write a program to show all non -prime
numbers in the entered range.
➢ Write a program to show and count the
number of words in a text file ‘DATA.TXT’
which is starting/ending with the word ‘The’,
‘the’.
➢ WAP to read data from a text file DATA.TXT,
and display each word with number of vowels
and consonants.
➢ WAP to read data from a text file DATA.TXT,
and display word which have maximum /
minimum characters.
➢ Write a program to write a string in the binary
file “comp.dat” and count the number of times
a character appears in the given string using a
dictionary.
➢ Write a program that will write a string in binary
file "school.dat" and display the words of the
string in reverse order.
CONTENT
➢ Write a program to insert list data in CSV File
and print it.
➢ Write a program that rotates the elements of a
list so that the element at the first index moves
to the second index, the element in the second
index moves to the third index, etc., and the
element in the last index moves to the first
index.
➢ Write a program to insert item on selected
position in list and print the updated list.
➢ Write a program to take 10 sample phishing
email, and find the most common word
occurring using List.
➢ Write an application program to interface
python with SQL database for employee’s data
insertion.
➢ Write an application program to interface
python with SQL database for employee’s data
deletion.
➢ Write an application program to interface
python with SQL database for employee’s data
updation.
CONTENT
➢ Write an application program to interface
python with SQL database for employee’s
data display.

➢ Write an application program to implement


Stack in Python using List.

➢ SQL COMMANDS.
Program 1: WAP to accept a string and whether it
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 Palindrome...")
Program 2: Write a program to show statistics of
characters in the given line (to counts the
number of alphabets, digits, uppercase,
lowercase).
str1 = input ("Enter the String:")
n=c=d=s=u=l=o=0
for ch in str1:
if ch.isalnum():
n+=1
if ch.isupper():
u=u+1
elif ch.islower():
l=l+1
elif ch.isalpha():
c=c+1
elif ch.isdigit():
d=d+1
elif ch.isspace():
s=s+1
else:
o=o+1
print("No. of Alpha and Digit",n)
print("No. of Capital Alpha",u)
print("No. of Small Alphabet",l)
print("No. of Digit",d)
print("No. of Spaces",s)
print("No. of Other Character",o)
Program 3: WAP to remove all odd numbers from
the given list.

L=[2,3,12,7,10,13,27]
for i in L:
if i%2==0:
L.remove(i)
print(L)
Program 4: WAP to display frequencies of all the
element of a list.

L=[3,21,5,6,3,8,21,6]
L1=[]
L2=[]
for i in L:
if i not in L2:
x=L.count(i)
L1.append(x)
L2.append(i)
print('element','\t\t',"frequency")
for i in range (len(L1)):
print(L2[i],'\t\t\t',L1[i])
Program 5: WAP to display those string which
starts with ‘A’ from the given list.

L=['ANUPAM','LEENA','ADITEY','HIMANSHI','NISHAN
T','AMRIT']
count=0
for i in L:
if i[0] in ('aA'):
count=count+1
print(i)
print("Appearing", count, "Times")
Program 6: WAP to find and display the sum of all
the values which are ending with 3 from a list.

L=[33,13,92,99,3,12]
sum=0
x=len(L)
for i in range(0,x):
if type(L[i])==int:
if L[i]%10==3:
sum+=L[i]
print("Sum of the values which are ending With 3
Is:",sum)
Program 7: Write a program to show sorting of
elements of a list step – by – step.

a=[16,10,2,4,9,18]
print("The Unsorted List is:",a)
print("The Sorting Starts now:")
n=len(a)
for i in range(n):
for j in range(0,n-i-1):
if a[j]>a[j+1]:
a[j],a[j+1]=a[j+1],a[j]
print("The List After Sorting " , i ,"Loop is",a)
print("The List After Sorting is",a)
Program 8: A list num contains the following
elements : 3,21,5,6,14,8,14,3 .WAP to swap the
content with next value, if it is divisible by 7 so
that the resultant array will look like :
3,5,21,6,8,14,3,14.

num=[3,21,5,6,14,8,14,3]
l=len(num)
i=0
while i<1:
if num[i]%7 == 0:
num[1], num[i+1] = num[i+1], num[i]
i=i+2
else:
i=i+1
print('The Elements of the List after Swapping is:',num)
Program 9: Write a program to accept values
from a user and create a tuple.

t=tuple()
n=int(input("Enter Limit:"))
for i in range(n):
a=input("Enter Number:")
t=t+(a,)
print("Output is")
print(t)
Program 10: WAP to input total number of
sections and stream name in 11th class and
display all information on the output screen.

classxi=dict()
n=int(input("Enter Total Number of Section in XI
Class:"))
i=1
while i<=n:
a=input("Enter Section:")
b=input("Enter Stream Name:")
classxi[a]=b
i=i+1
print("Class",'\t',"Section",'\t',"Stream Name")
for i in classxi:
print("XI",'\t',i,'\t\t',classxi[i])
Program 11: Write a Program using python to find
the Occurrence of any word in a string.

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 ## ")
Program 12: Write a program to show all non -
prime numbers in the entered range.

def nprime(lower,upper):
print("“SHOW ALL NUMBERS EXCEPT PRIME
NUMBERS WITHIN THE RANGE”")
for i in range(lower, upper+1):
for j in range(2, i):
ans = i % j
if ans==0:
print (i,end=' ')
break

lower=int(input("Enter Lowest Number as Lower


Bound to Check : "))
upper=int(input("Enter Highest Number as Upper
Bound to Check: "))
reply=nprime(lower,upper)
print(reply)
Program 13: Write a program to show and count
the number of words in a text file ‘DATA.TXT’
which is starting/ending with the word ‘The’,
‘the’.

f1=open("data.txt","r")
s=f1.read()
print("All Data of File in String:",s)
print("*"*66)
count=0
words=s.split()
print("All Words: ",words,", length is ",len(words))
for word in words:
if word.startswith("the")==True: # word.ends
with(“the”)
count+=1
print("Words start with 'the' is ",count)
Program 14: WAP to read data from a text file
DATA.TXT, and display each word with number of
vowels and consonants.

f1=open("data.txt","r")
s=f1.read()
print(s)
countV=0
countC=0
words=s.split()
print(words,", ",len(words))
for word in words:
countV=0
countC=0
for ch in word:
if ch.isalnum()==True:
if ch=='a' or ch=='e' or ch=='i' or ch=='o' or
ch=='u':
countV+=1
else:
countC+=1
print("Word : ",word,", V: ",countV,", C= ", countC)
Program 15 : WAP to read data from a text file
DATA.TXT, and display word which have
maximum / minimum characters.

f1=open("data.txt","r")
s=f1.read()
print(s)
words=s.split()
print(words,", ",len(words))
maxC=len(words[0])
minC=len(words[0])
minfinal=""
maxfinal=""
for word in words[1:]:
length=len(word)
if maxC<length:
maxC=length
maxfinal=word
if minC>length:
minC=length
minfinal=word
print("Max word : ",maxfinal,", maxC: ",maxC)
print("Min word : ",minfinal,", minC: ",minC)
Program 16 : Write a program to write a string in
the binary file “comp.dat” and count the number
of times a character appears in the given string
using a dictionary.

('comp.dat','wb')
pickle.dump(str,f1)
print("The string is written in the ",f1.name, "file")
f1.close()
f1=open('comp import pickle')
str="This is the Computer Science with Python Class"
f1=open.dat,'rb'
str=pickle.load(f1)
print("\n\nThe string in the binary file is : \n",str)
d={}
for x in str:
if x not in d:
d[x]=1
else:
d[x]=d[x]+1
print("\nThe occurrences of each letter of string is :\n",
d)
f1.close()
PROGRAM 17: Write a program that will write a
string in binary file "school.dat" and display the
words of the string in reverse order.

f1=open('school.dat','rb')
str1=pickle.load(f1)
print("\n\nthe string in the binary file is : \n",str1)
str1=str.split(" ")
l=list(str1)
print("\nthe list is ",l)
length=len(l)
while length>0:
print(l[length-1],end=" ")
length-=1
Program 18: Write a program to insert list data in
CSV File and print it.

import csv
fields = ['Name', 'Branch', 'Year', 'CGPA']
rows = [ ['Nikhil', 'COE', '2', '9.0'], ['Sanchit', 'COE', '2',
'9.1'],
['Aditya', 'IT', '2', '9.3'], ['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'], ['Sahil', 'EP', '2', '9.1']]
filename = "MYCSV.csv"
with open(filename, 'w') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
with open('MYCSV.csv', newline='') as File:
reader = csv.reader(File)
for row in reader:
print(row)
Program 19: Write a program that rotates the
elements of a list so that the element at the first
index moves to the second index, the element in
the second index moves to the third index, etc.,
and the element in the last index moves to the
first index.

n=int(input("Enter Number of items in List: "))


DATA=[]
for i in range(n):
item=int(input("Item :%d: "%(i+1)))
DATA.append(item)
print("Now List Items are :",DATA)
lg=len(DATA)
print("Now Number of items before update are :",lg)
b=["undef"]*lg
for x in (range(lg-1)):
if (x)>lg:
break
b[x+1]=DATA[x]
b[0]=DATA[-1]
print("RESULT OF NEW LIST IS " , b)
Program 20: Write a program to insert item on
selected position in list and print the updated
list.

n=int(input("Enter Number of items in List: "))


DATA=[]
for i in range(n):
item=int(input("Item :%d: "%(i+1)))
DATA.append(item)
print("Now List Items are :",DATA)
print("Now Number of items before update are
:",len(DATA))
e=int(input("Enter Item = "))
pos=int(input("Enter POS = "))
DATA.append(None)
le=len(DATA)
for i in range(le-1,pos-1,-1):
DATA[i]=DATA[i-1]
print("Now List Items are :",DATA)
DATA[pos-1]=e
print("Now Number of items are :",len(DATA))
print("Now Updated List Items are :",DATA)
PROGRAM 21: Write a program to take 10 sample
phishing email, and find the most common word
occurring using List.
phishingemail=[
"jackpotwin@lottery.com",
"claimtheprize@mymoney.com",
"youarethewinner@lottery.com",
"luckywinner@mymoney.com",
"spinthewheel@flipkart.com",
"dealwinner@snapdeal.com",
"luckywinner@snapdeal.com",
"luckyjackpot@americanlottery.com",
"claimtheprize@lootolottery.com",
"youarelucky@mymoney.com"
]
myd={}
for e in phishingemail:
x=e.split('@')
for w in x:
if w not in myd:
myd[w]=1
else:
myd[w]+=1
key_max = max(myd,key=myd.get)
print("Most Common Occurring word is :",key_max)
PROGRAM 22: Write an application program to
interface python with SQL database for
employee’s data insertion.
import mysql.connector as m
def insertion():
try:
con=m.connect(host='localhost',user='root',password='
Bhardwaj',database='SAMPLE')
if(con.is_connected()):
print('Successfully connected')
mycur=con.cursor()
empid=int(input("Enter EMPLOYEE ID :"))
empname= input("Enter EMPLOYEE NAME :")
query="insert into employee values
({},'{}')".format(empid,empname)
mycur.execute(query)
con.commit()
print ("Record inserted successfully")
mycur.close();
con.close()
except Exception as e:
print(e)
#Main block
insertion()
PROGRAM 23: Write an application program to
interface python with SQL database for
employee’s data deletion.
import mysql.connector as m
def deletion():
try:
con=m.connect(host='localhost',user='root',password='
Bhardwaj',database='SAMPLE')
if(con.is_connected()):
print('successfully connected')
mycur=con.cursor()
empid=int(input("Enter Employee ID to be deleted
:"))
query="DELETE FROM EMPLOYEE WHERE
ID={}".format(empid)
mycur.execute(query)
con.commit()
print ("Record deleted successfully")
mycur.close();
con.close()
except Exception as e:
print(e)
#Main Block
deletion()
PROGRAM 24: Write an application program to
interface python with SQL database for
employee’s data updation.
import mysql.connector as m
def updation():
try:
con=m.connect(host='localhost',user='root',password='Bhard
waj',database='SAMPLE')
if(con.is_connected()):
print('successfully connected')
mycur=con.cursor()
empid=int(input("Enter Employee ID to be update :"))
empname= input("Enter new name of employee :")
query="UPDATE EMPLOYEE SET NAME ='{}' WHERE
ID={}".format(empname,empid)
mycur.execute(query)
con.commit()
print ("Record Updated Successfully")
mycur.close();
con.close()
except Exception as e:
print(e)
#Main Block
updation()
PROGRAM 25: Write an application program to
interface python with SQL database for
employee’s data display.
import mysql.connector as m
def display():
try:
con=m.connect(host='localhost',user='root',password='Bhard
waj',database='SAMPLE')
if(con.is_connected()):
print('successfully connected')
mycur=con.cursor()
query="SELECT * FROM EMPLOYEE"
mycur.execute(query)
myrows=mycur.fetchall()
print ("Records in Employee table are:")
for row in myrows:
print(row)
print("all rows printed successfully!")
mycur.close();
con.close()
except Exception as e:
print(e)
#Main block
display()
PROGRAM 26: Write an application program to
implement Stack in Python using List.
def isEmpty(S):
if len(S)==0:
return True
else:
return False

def Push(S,item):
S.append(item)
top=len(S)-1

def Pop(S):
if isEmpty(S):
return "Underflow"
else:
val = S.pop()
if len(S)==0:
top=None
else:
top=len(S)-1
return val

def Peek(S):
if isEmpty(S):
return "Underflow"
else:
top=len(S)-1
return S[top]

def Show(S):
if isEmpty(S):
print("Sorry No items in Stack ")
else:
t = len(S)-1
print("(Top)",end=' ')
while(t>=0):
print(S[t],"<==",end=' ')
t-=1
print()

# main begins here


S=[] #Stack
top=None
while True:
print("**** STACK DEMONSTRATION ******")
print("1. PUSH ")
print("2. POP")
print("3. PEEK")
print("4. SHOW STACK ")
print("0. EXIT")
ch = int(input("Enter your choice :"))
if ch==1:
val = int(input("Enter Item to Push :"))
Push(S,val)
elif ch==2:
val = Pop(S)
if val=="Underflow":
print("Stack is Empty")
else:
print("\nDeleted Item was :",val)
elif ch==3:
val = Peek(S)
if val=="Underflow":
print("Stack Empty")
else:
print("Top Item :",val)
elif ch==4:
Show(S)
elif ch==0:
print("Bye")
break
OUTPUT
SQL
COMMANDS
1. Creating Databases:

2. Opening Databases:

3. Creating a Table:

4. Viewing a Table Structure:


5. Query to Insert Values in a Table:

6.Query to Display Values in a Table:


7. Query to Select Data from Table Where
Department is CS:

8. Query to Select Name from Table


Where Salary Between 3000 And 5000:

9. Query to Select Data from Table Where


EID is 3:

10. Query to Select Distinct Department


from table:
11. Query to Select Average Salary from
Table Group by Gender:

12. Query to Select ENAME & EID from


Table Where ENAME ends with A:

13. Query to Select Minimum Salary


from Table:
14. Query to Select Maximum Salary
from Table:

15. Query to Count Number of


Employees from Table:

16. Query to Count Number of


Employees Group by Gender from
Table:
17. Query to Increase Salary of
Employees by 3000 from Table:

18. Query to Display ENAME & SALARY


from Table:
19. Query to Select Sum of Salary &
Group by Department from Table:

20. Query to Delete Records of


Employee Whose EID is 2 from Table:

21. Query to Display Values in a Table:


22. Query to Add New Column in Table
Employee:

23. Query to Viewing a Table Structure:


24. Query to Delete Table Employee:

To Delete Records Present in Table: –

To Delete Table: –

To check Records in Table: –

To check Table in Database: –


25. Query to Show Table
Structure:

You might also like