Download as pdf or txt
Download as pdf or txt
You are on page 1of 36

ST.

MARY’S INTER COLLEGE, ETAWAH

LIST OF PROGRAMS FOR CLASS XII PRACTICAL RECORD

Q.1) Write a menu driven program in python to display Fibonacci


series of a given number or print factorial of a given no.

Ans:
ch='Y'
while (ch=='Y' or ch=='y'):
print("Enter 1 : fibonacci series:")
print("Enter 2 : factorial:")
opt=int(input('enter ur choice:='))
if opt==1:
n=int(input('enter no. of terms:'))
no1=0
no2=1
x=0
print("The first ",n, "terms of the fibonacci series is:")
print(no1,no2,end=" ")
while(x<=(n-2)):
no3=no1+no2
no1=no2
no2=no3
print (no3,end=" ")
x=x+1
elif opt==2:
f=1
n=int(input('enter no:'))
for i in range(1,n+1):
f=f*i
print('factorial is:',f)
else:
print('invalid choice')
ch=(input('want to continue?'))
Q.2) Write a menu driven code in python to check whether a string is
palindrome or not or check whether one number is prime or not.

Ans:
ch='Y'
while (ch=='Y' or ch=='y'):
print("Enter 1 : String palindrome:")
print("Enter 2 : prime no:")
opt=int(input('enter ur choice:='))
if opt==1:
str=input('Enter Text:=')
rev=str[::-1]
if str==rev:
print(str, "is Palindrome")
else:
print(str, "is not Palindrome")
elif opt==2:
no=int(input('Enter Number : '))
for i in range(2,no):
ans=no%i
if ans==0:
print ("The given number is not a Prime Number")
break;
else: # Loop else
print("The given number is a Prime Number")
else:
print('invalid choice')
ch=(input('want to continue? Y/N'))
Q 3) Write a program to accept a set of integers and find whether those
numbers are palindromes or not.

n1=0
while True :
a = input("enter a number (for quit enter q = ")
if a == "q" or a== "Q" :
break
else :
n=int(a)
while n>0:
d=n%10
n1=n1*10+d
n=n//10

if int(a) == n1 :
print(n1,"is palindromes of ", int(a))
else :
print(n1,"is not palindromes of ",int(a))
n1=0
Q.4) Write a program that prompts for a phone number of 10 digit and two
dashes, with dashes after the area code and the next three numbers.

Eg. 017-555-1212 is a valid input.

Your program should check whether the phone number entered is in valid
format or not and display the appropriate messages on your screen.

num = input("enter your phone number = ")

if len(num)== 12 :

if num[3]== "-" :

if num[4:7].isdigit() :

if num [7]== "-":

if num[ 8 : 13 ].isdigit() :

if num[ : 3 ].isdigit() :

t=1

else :

t=0

else :

t=0

else :

t=0

else :
t=0

else :

t=0

else :

t=0
if t==1:
print (num,‟is a valid phone number‟)
else:
print (num,‟is not a valid phone number‟)
Q.5) Write a program that prompts the user to type some sentence (s) followed
by “enter key”, it should then print the original sentence (s) and the following
statistics relating to sentence (s) :

I = number of words

II = numbers of character (including white-space and punctuation )

III = percentage of character that are alphanumeric.

Answer =

sen = input("enter a sentance = ")


count = 1
alp = 0
for j in sen :
if j == " " :
count += 1
elif j.isalnum() :
alp += 1
print("number of word is ",count)
print("number of characters ",len(sen))
print("percentage of alpha numeric = ", (alp / len(sen)) * 100)
Q.6) Write a python program by using a function to search for an
element in a given list.

Ans:

def lsearch(ar,n,item):
for i in range(0,n):
if ar[i]==item:
return i
return -1

n=int(input('enter size of list:'))


print('enter numbers in sorted order:\n')
ar=[0]*n
for i in range(n):
ar[i]=int(input('Enter the element '))
item=int(input('enter no. to be searched:'))
index=lsearch(ar,n,item)
if index!=-1:
print('\n element found at index :',index,',position: ',(index+1))
else:
print('\n sorry, the given number is not found')
Q.7) Write a program by using a function to find the sum of the following
series:

x – x2 /2! + x3/3! – …….. – x6/6!

Ans:

def sumseries(x):
fact = 1
sum = 0
for i in range(1,7):
fact = fact * i
if i % 2 == 0 :
sum = sum - (x**i)/fact
else :
sum = sum + (x**i)/fact
print("Sum of the given series = ",sum)

x = int(input("enter a term = "))


sumseries(x)
Q.8 Write a program to have following functions:

(i) A function that takes a number as argument and calculates cube for it.
The function does not return a value .If there is no value passed to the
function in function call, the function should calculate cube of 2.

(ii) A function that takes two char arguments and returns True if both the
arguments are equal otherwise False.

Test both these functions by giving appropriate function call statements.

(i)
def cube( a = 2 ) :
print( "Cube of ", a ,"=" , a ** 3 )

num = input("Enter a number (For empty press Enter ) :")


if num == "" :
cube()
else :
cube( int (num) )
(ii)
def chr() :
char1 = input("Enter a Char 1 : ")
char2 = input("Enter a Char 2 : ")
if char1 == char2 :
print("Ture")
else:
print("False ")

chr()
Q. 9) Write a function that takes two numbers and returns the number that
has minimum one's digit

[For example, if numbers passed are 491 and 278, then the function will
return 491 because it has got minimum one's digit out of two given
numbers (491's 1 is < 278's 8)].

def min(x , y ) :

a = x % 10

b = y % 10

if a < b :

return x

else :

return y

first = int(input("Enter first number = "))

second = int(input("Enter second number = "))

print ( "Minimum one's digit number = " , min( first , second ) )


Q.10) Write a program that generates a series using a function which takes
first and last values of the series and then generates four terms that are
equidistant e.g., if two numbers passed are 1 and 7 then function returns 1
3 5 7.

def ser( a , b ) :

d = int ( ( b - a ) / 3 )

print("Series = " , a , a + d , a + 2*d , b )

first = int(input("Enter first Term = "))

last = int(input("Enter last Term = "))

ser(first , last )
Q.11) Write a menu driven python code to display the content of the text
file „abc.txt‟ with those lines which have first character 'g' & count all the
line having 'a' as last character and also print the lines.

Ans:
ch='Y'
while (ch=='Y' or ch=='y'):
print("Enter 1 : lines start with g:")
print("Enter 2 : count lines end with a :")
opt=int(input('enter ur choice:='))
if opt==1:
file=open("abc.txt" , "r")
line=file.readline( )
while line:
if line[0]=="g" :
print(line)
line=file.readline( )
file.close( )
elif opt==2:
count =0
f=open("abc.txt","r")
data=f.readlines()
for line in data:
l=len(line)
if line[l-2] == 'a':
print(line)
count=count+1
print("Number of lines having 'a' as last character is/are : " ,count)
f.close()
else:
print('invalid choice')
ch=(input('want to continue?'))
Q.12) Write a menu driven program in python to read text file „abc.txt‟
and display
● No. of words
● No. of lines
● No. of alphabets
Ans:-
ch='Y'
while (ch=='Y' or ch=='y'):
print("Enter 1 : count words:")
print("Enter 2 : count line:")
print("Enter 3 : count alphabets:")
print("Enter 4 : exit:")
opt=int(input('enter ur choice:='))
if opt==1:
f=open("abc.txt","r")
linesList=f.readlines()
count=0
for line in linesList:
wordsList=line.split()
print(wordsList)
count = count+ len(wordsList)
print("The number of words in this file are : ",count)
f.close()
elif opt==2:
c=0
f=open("abc.txt","r")
line=f.readline()
while line:
c=c+1
line=f.readline()
print('no. of lines:',c)
f.close( )
elif opt==3:
F=open('abc.txt','r')
c=0
for line in F:
words=line.split()
for i in words:
for letter in i:
if(letter.isalpha()):
c=c+1
print('Total no. of alphabets are:',c)
elif opt==4:
break
else:
print('invalid choice')
ch=(input('want to continue?'))
13. Consider the following definition of dictionary member; write a
method in python to write the content in a pickled file member.dat. Also
write another method to search and display the content of the pickled file
member.dat, where „MemberNo‟ key of the dictionary is matching with
1005

member={„MemberNo‟:________,‟Name‟:________}

Ans.

def WRITEMEMBER():
import pickle
member={ }
memfile=open('member.dat','wb')
ans='y'
while ans=='y' or ans=='Y':
mno=int(input('Enter the Member Number'))
mname=input('Enter the Member Name')
member['MemberNo']=mno
member['Name']=mname
pickle.dump(member,memfile)
ans=input('Do you want to enter more records (Y/N)….')
memfile.close()

def DISPLAYSTAFF():
import pickle
member={}
memfile=open('member.dat','rb')
found=False
try:
print('The details of members with Member No. 1005')
while True:
member=pickle.load(memfile)
if member['MemberNo']==1005:
print(member)
found=True
except EOFError:
if found== False:
print('No such records found')
else:
print('Search Successful')
memfile.close()
WRITEMEMBER()
DISPLAYSTAFF()
14. Write a Python program to write a nested Python list( contains
Item_Name, description and price) to a CSV file in one go. After writing
the CSV file, read the CSV file and display the content.
Ans:-

import csv

fh=open('items.csv','w')

iwriter=csv.writer(fh)

ans="y"

itemrec=[["Item_Name","Description","Price"]]

print("Enter item details")

while ans=="y":

iname=input("Enter Item Code :")

desc=input("Enter description :")

price=float(input("Enter price :"))

itemrec.append([iname,desc,price])

ans=input("Do you want to enter more Items (Y/N)….")

else:

iwriter.writerows(itemrec)

print("Records written successfully")

fh.close()

fh=open("items.csv","r",newline='\r\n')

ireader=csv.reader(fh)

for rec in ireader:

print(rec)

fh.close()
Q15. Write a python code to add a student using mysql connectivity. You are
requested to display the entire content of the student table also.
Create database and table as below:
Name of database =school
Name of table = student (roll, name, age, class, city)
[Apply the following commands in mysql
create database school;
create table student(roll integer, name char(20), age integer, class char(5),
city char(20)); ]

Ans:
import mysql.connector

mydb=mysql.connector.connect(host="localhost", user="root",
passwd="Smic123@", database="school")
mycursor=mydb.cursor()

ch='Y'

while ch=='Y' or ch=='y':

roll=int(input("Enter the roll number : "))

name=input("Enter the Name: ")

age=int(input("Enter Age of Student : "))

class1=input("Enter the Class : ")

city=input("Enter the City of the Student : ")

stud=(roll,name,age,class1,city)

sql="insert into student (roll,name,age,class,city) values


(%s,%s,%s,%s,%s)"

mycursor.execute(sql,stud)

mydb.commit()
print('One Record added successfully!!!')

ch=(input('Do you want to continue? Y/N'))

mycursor.execute("select * from student")

res=mycursor.fetchall()

print("The Students details are as follows : ")

print("(ROll, Name, Age, Class, City)")

for x in res:

print(x)

mydb.close()
Q.16 Write a python code to delete a student as per given roll number by
using mysql connectivity. Program should display the contents of student table
before and after deletion. Create the database and table as below:
Name of database =school
Name of table = student(roll,name,age,class,city)

Ans:

import mysql.connector
mydb=mysql.connector.connect(host="localhost", user="root",
passwd="Smic123@", database="school")
mycursor=mydb.cursor()
roll=int(input("Enter the roll number of the student to be deleted : "))
rl=(roll,)
mycursor.execute("select * from student")
res=mycursor.fetchall()
print("The Students details before deletion are as follows : ")
print("(ROll, Name, Age, Class, City)")
for x in res:
print(x)

sql="delete from Student where roll=%s"


mycursor.execute(sql,rl)
print('Record deleted!!!')
mydb.commit()

mycursor.execute("select * from student")


res=mycursor.fetchall()
print("The Students details after deletion are as follows : ")
print("(ROll, Name, Age, Class, City)")
for x in res:
print(x)

mydb.close()
Q.17) Write a python code to search a student as per given roll number in
database using mysql connectivity and show its result.
Create database and table as below:
Name of database =school
Name of table = student(roll,name,age,class,city)
Ans:
import mysql.connector
mydb=mysql.connector.connect(host="localhost", user="root",
passwd="Smic123@", database="school")
mycursor=mydb.cursor()

s=int(input("Enter roll no to search: "))

rl=(s,)

sql="select * from student where roll=%s"

mycursor.execute(sql,rl)

res=mycursor.fetchall()

if not res :

print("The Given Roll no is not found : ")

else:

print("The Students details are as follows : ")

print("(ROll, Name, Age, Class, City)")

for x in res:

print(x)

mydb.close()
Q 18 = Write a python code to search a student as per given roll number
in database and if the roll number is found then modify the city of that
particular student by accepting a new city name from user. Program
should display the details before and after modification.

Answer =

import mysql.connector
mydb=mysql.connector.connect(host="localhost", user="root",
passwd="Smic123@", database="school")
mycursor=mydb.cursor()
s=int(input("Enter roll no to be searched: "))
rl=(s,)
sql="select * from student where roll=%s"
mycursor.execute(sql,rl)
res=mycursor.fetchall()
if not res :
print("The Given Roll no is not found : ")
else:
c=input("Enter the new city name : ")
print("The Students details before modification is as follows : ")
print("(ROll, Name, Age, Class, City)")
for x in res:
print(x)
r2=(c,s)
sql="update student set city= %s where roll=%s"
mycursor.execute(sql,r2)
mydb.commit()
print("Record updated successfully!!!! ")
sql="select * from student where roll=%s"
mycursor.execute(sql,rl)
res=mycursor.fetchall()
print("The Students details after modification is as follows : ")
print("(ROll, Name, Age, Class, City)")
for x in res:
print(x)
mydb.close()
Q.19) Write a menu driven python code to perform push and pop operations on
a stack which contains bookname.
Ans:
stk=[]
while True:
print("Enter 1 : Push")
print("Enter 2 : Pop")
print("Enter 3 : Display Stack")
print("Enter 4 : Exit")
opt=int(input('enter ur choice:='))
if opt==1:
d=(input("enter book name : "))
stk.append(d)
elif opt==2:
if (stk==[]):
print( "Stack empty")
else:
p=stk.pop()
print ("Deleted element:", p)
elif opt==3:
if (stk==[]):
print( "Stack empty")
else:
print ("The stack content is :")
print(stk)
elif opt==4:
break
else:
print('invalid choice')
Q.20 A dictionary containing names and marks as key value pairs of 6
students. Write a program, with separate user defined functions to perform the
following operations:

● Push the keys (name of the student) of the dictionary into a stack,
where the corresponding value (marks) is greater than 75.
● Pop and display the content of the stack.
For example:
If the sample content of the dictionary is as follows:
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90,"TOM":82}

The output from the program should be:

TOM ANU BOB OM

Ans.
R={"OM":76, "JAI":45, "BOB":89, "ALI":65, "ANU":90, "TOM":82}
def PUSH(S,N):
S.append(N)
def POP(S):
if S!=[]:
return S.pop()
else:
return None
ST=[]
for k in R:
if R[k]>75:
PUSH(ST,k)
while True:
if ST!=[]:
print(POP(ST),end=" ")
else:
break
Q.21 A file contains a list of telephone numbers in the
following form: Arvind 7258031 Sachin 7259197 . The
names contain only one word the names and telephone
numbers are separated by white spaces Write program
to read a file and display its contents in two columns.

print("Name | Phone no. ")

file = open("portal.txt", "r")

lst = file.readlines()

for i in lst :

data = i.split()

print( data[0] ,end = "\t" )

print("|" , end = "\t")

print ( data[1] )

file.close()
Q.22 Write a program to count the words "to" and "the"
present in a text file "Poem.txt".

to_no = 0

the_no = 0

file = open("Poem.txt", "r")

lst = file.readlines()

for i in lst :

word = i.split()

for j in word :

if j == "to" :

to_no += 1

elif j == "the" or j == "The" :

the_no += 1

print("Number 'to' : " , to_no)

print("Number 'the' : " , the_no)

file.close()
Q.23 Write a program to count the number of upper-
case alphabets present in a text file "Article.txt".

count = 0

file = open("Article.txt","r")

sen = file.read()

for i in range ( len(sen) ) :

if sen[ i ].isupper() :

count += 1

print("Number of upper case alphabet : ", count)

file.close()
Q.24 Write a method/function DISPLAYWORDS() in
python to read lines from a text file STORY.TXT, and
display those words, which are less than 4 characters.

def DISPLAYWORDS() :

file = open("story.txt", "r")

lst = file.readlines()

for i in lst :

word = i.split()

for j in word :

if len( j ) < 4 :

print( j )

file.close()

DISPLAYWORDS()
Q.25 Write a function in Python to count and display the
number of lines starting with alphabet 'A' present in a
text file " LINES.TXT". e.g., the file "LINES.TXT" contains
the following lines: A boy is playing there. There is a
playground. An aeroplane is in the sky. Alphabets &
numbers are allowed in password. The function should
display the output as 3.

count = 0

file = open("LINES.txt","r")

lst = file.readlines()

for i in lst :

if i[ 0 ] == "A" :

print(i)

count += 1

print("Number of sentences started with A : ",count)

file.close()

Q.26
Q.27 Write a program in python to replace all words „the‟ by
another word „them‟ in a text file poem.txt.

f=open('poem.txt')
d=f.read()
print('The original content of the file Poem.txt is')
print(d)
d=d.replace('the','them')
f.close()
f=open('poem.txt','w')
f.write(d)
f.close()
print('The content of the file Poem.txt after modification is')
f=open('poem.txt')
d=f.read()
print(d)
f.close()

Q.28 Write a program in python to replace a character by


another character in a file „story.txt‟. Accept both the characters
from user.

f=open('story.txt')
d=f.read()
print('The original content of the file story.txt is')
print(d)
n1=input('Enter the character to be searched')
n2=input('Enter the character to be replaced')
d=d.replace(n1,n2)
f.close()
f=open('story.txt','w')
f.write(d)
f.close()
print('The content of the file story.txt after modification is')
f=open('story.txt')
d=f.read()
print(d)
f.close()

Q.29 Write a program in python to read a file „data.txt‟ and


display only those lines whose length is more than 20 characters.

f=open('data.txt')
d=f.readlines()
print('The original content of the file data.txt is')
for i in d:
print(i)
print('In file poem.txt lines with more than 20 characters is')
for i in d:
if len(i)>20:
print(i)
f.close()

Q.30 Write a program in python to replace all duplicate lines


from the file story.txt.

f=open('story.txt')
d=f.readlines()
print('The original content of the file story.txt is')
for i in d:
print(i,end='')
m=[]
for i in d:
if i not in m:
m.append(i)
f.close()
f=open('story.txt','w')
for i in m:
f.write(i)
f.close()
print('The content of the file story.txt after removing duplicate
lines is')
f=open('story.txt')
d=f.readlines()
for i in d:
print(i,end='')
f.close()

You might also like