[go: up one dir, main page]

0% found this document useful (0 votes)
98 views26 pages

Smic Class Xii Python Practicals-2021

I. The document contains sample code for various Python programming questions related to lists, strings, functions, files etc. II. It includes menu driven programs to perform tasks like displaying Fibonacci series or factorial, checking palindrome strings or prime numbers, searching elements in lists using functions. III. Other questions involve generating series using functions, reading and processing text files to count words, lines, alphabets, pickling dictionary data to a file and searching contents.

Uploaded by

Aryan Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views26 pages

Smic Class Xii Python Practicals-2021

I. The document contains sample code for various Python programming questions related to lists, strings, functions, files etc. II. It includes menu driven programs to perform tasks like displaying Fibonacci series or factorial, checking palindrome strings or prime numbers, searching elements in lists using functions. III. Other questions involve generating series using functions, reading and processing text files to count words, lines, alphabets, pickling dictionary data to a file and searching contents.

Uploaded by

Aryan Yadav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

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() :

print("it is vaild number ")

else :

print("it is not vaild number ")

else :

print("it is not vaild number ")

else :

print("it is not vaild number ")

else :

print("it is not vaild number ")


else :

print("it is not vaild number ")

else :

print("it is not vaild 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')

You might also like