Smic Class Xii Python Practicals-2021
Smic Class Xii Python Practicals-2021
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.
Your program should check whether the phone number entered is in valid
format or not and display the appropriate messages on your screen.
if len(num)== 12 :
if num[3]== "-" :
if num[4:7].isdigit() :
if num[ 8 : 13 ].isdigit() :
if num[ : 3 ].isdigit() :
else :
else :
else :
else :
else :
I = number of words
Answer =
Ans:
def lsearch(ar,n,item):
for i in range(0,n):
if ar[i]==item:
return i
return -1
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)
(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.
(i)
def cube( a = 2 ) :
print( "Cube of ", a ,"=" , a ** 3 )
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
def ser( a , b ) :
d = int ( ( b - a ) / 3 )
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"]]
while ans=="y":
itemrec.append([iname,desc,price])
else:
iwriter.writerows(itemrec)
fh.close()
fh=open("items.csv","r",newline='\r\n')
ireader=csv.reader(fh)
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'
stud=(roll,name,age,class1,city)
mycursor.execute(sql,stud)
mydb.commit()
print('One Record added successfully!!!')
res=mycursor.fetchall()
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)
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()
rl=(s,)
mycursor.execute(sql,rl)
res=mycursor.fetchall()
if not res :
else:
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')