Xii Cs Practicals Final
Xii Cs Practicals Final
/, // and %.
Solution:
result = 0
if op == "+":
elif op == "-":
elif op == "*":
elif op == "/":
if val2 == 0:
else:
elif op == "//":
else:
Solution:
def pernum(num):
divsum=0
for i in range(1,num):
if num%i == 0:
divsum+=i
if divsum==num:
print('Perfect Number')
else:
pernum(6)
pernum(15)
Program 23: Write a Program to check if the entered number is Armstrong or not.
Solution:
#An Armstrong number has sum of the cubes of its digits is equal to the number itself
no1 = no
sum = 0
while(no>0):
ans = no % 10;
if sum == no1:
print("Armstrong Number")
else:
Solution:
fact = 1
i=1
while i<=num:
fact = fact*i
i=i+1
Solution:
#fibonacci
x=0
y=1
z=1
while(z<= i):
x=y
y=z
z=x+y
Program 26: Write a Program to enter the string and to check if it’s palindrome or not using loop.
Solution:
# Program to enter the string and check if it’s palindrome or not using ‘for’ loop.
newlist=[]
newlist[:0]=msg
l=len(newlist)
ed=l-1
for i in range(0,l):
if newlist[i]!=newlist[ed]:
break
if i>=ed:
break
l=l-1
ed = ed - 1
Program 28: Write a Program to show the outputs based on entered list.
Solution:
my_list = ['p','r','o','b','e']
# Output: p
print(my_list[0])
# Output: o
print(my_list[2])
# Output: e
print(my_list[4])
# Nested indexing
# Output: a
print(n_list[0][1],n_list[0][2],n_list[0][3])
# Output: 5
print(n_list[1][3])
Program 29: Write a Program to enter the numbers in a list using split () and to use all the functions
related to list.
Solution:
#Program to enter the numbers in a list using split () and to use all the functions related to
list.
# print (len(numbers))
memo=[]
memo.insert(i,x)
i+=1
print(memo)
memo.append(25)
print("Second List")
print(memo)
newlist=[]
newlist[:0]=msg
l=len(newlist)
print(l)
Program 30: Write a Program to enter the number and print the Floyd’s Triangle in
decreasing order.
Solution:
#Floyd's triangle
for i in range(5,0,-1):
for j in range(5,i-1,-1):
print('\n')
Program 31: Write a Program to find factorial of entered number using user-defined module
fact().
Solution:
#Using function
import factfunc
ans=factfunc.fact(x)
print (ans)
Program 32: Write a Program to enter the numbers and find Linear Search, Binary Search,
Lowest Number and Selection Sort using list/array code.
Solution:
arr=[]
def array_operation():
ch=1
while ch!=10:
print('10 Exit\n')
if ch==1 :
appendarray()
elif ch==2 :
print_array()
elif ch==3 :
reverse_array()
elif ch==4 :
linear_search()
elif ch==5 :
binary_search()
elif ch==6 :
min_number()
elif ch==7 :
selection_sort()
def appendarray():
for i in range(0,10):
arr.insert(i,x)
def print_array():
for i in range(0,10):
print(arr[i]),
def reverse_array():
for i in range(1,11):
print(arr[-i]),
def lsearch():
try:
n=arr.index(x)
except:
def linear_search():
x=int(input('Enter the Number you want to search : '))
fl=0
for i in range(0,10):
if arr[i]==x :
fl=1
print ('Number Found at %d location'% (i+1))
break
if fl==0 :
def binary_search():
fl=0
low=0
heigh=len(arr)
while low<=heigh :
mid=int((low+heigh)/2)
if arr[mid]==x :
fl=1
break
elif arr[mid]>x :
low=mid+1
else :
heigh=mid-1
if fl==0 :
def min_number():
n=arr[0]
k=0
for i in range(0,10):
if arr[i]<n :
n=arr[i]
k=i
def selection_sort():
for i in range(0,10):
n=arr[i]
k=i
for j in range(i+1,10):
if arr[j]<n :
n=arr[j]
k=j
arr[k]=arr[i]
arr[i]=n
array_operation()
Program 34: Write a Program to read data from data file and show Data File Handling
related functions utility in python.
Solution:
f=open("test.txt",'r')
print(f.name)
f_contents=f.read()
print(f_contents)
f_contents=f.readlines()
print(f_contents)
f_contents=f.readline()
print(f_contents)
for line in f:
print(line, end='')
f_contents=f.read(50)
print(f_contents)
size_to_read=10
f_contents=f.read(size_to_read)
while len(f_contents)>0:
print(f_contents)
print(f.tell())
f_contents=f.read(size_to_read)
Program 35: Write a Program to read data from data file in append mode and use
writeLines function utility in python.
Solution:
af=open("test.txt",'a')
af.writelines('\n' + lines_of_text)
af.close()
Program 36: Write a Program to read data from data file in read mode and count the
particular word occurrences in given string, number of times in python.
Solution:
f=open("test.txt",'r')
read=f.readlines()
f.close()
times=0 #the variable has been created to show the number of times the loop runs
times2=0 #the variable has been created to show the number of times the loop runs
count=0
line=sentence.split()
times+=1
line2=each
times2+=1
if chk==line2:
count+=1
print("The search String ", chk, "is present : ", count, "times")
print(times)
print(times2)
Program 38: Write a Program to read data from data file in read mode and append the
words starting with letter ‘T’ in a given file in python.
Solution:
#Program to read data from data file in read mode and
f=open("test.txt",'r')
read=f.readlines()
f.close()
id=[]
for ln in read:
if ln.startswith("T"):
id.append(ln)
print(id)
Program 39: Write a Program to show MySQL database connectivity in python.
Solution:
import mysql.connector
con=mysql.connector.connect(host='localhost',user='root',password='',db='school')
stmt=con.cursor()
stmt.execute(query)
data=stmt.fetchone()
print(data)
Program 40: Write a Python program to implement all basic operations of a stack, such as
adding element (PUSH operation), removing element (POP operation) and displaying the
stack elements (Traversal operation) using lists.
Solution:
s=[]
c="y"
while (c=="y"):
if (choice==1):
s.append(a)
elif (choice==2):
if (s==[]):
else:
elif (choice==3):
l=len(s)
print (s[i])
else:
print("Wrong Input")
Solution:
#using Stack
vowels =['a','e','i','o','u']
Stack = []
if letter in vowels:
Stack.append(letter)
print(Stack)
Solution:
a=[]
c='y'
while (c=='y'):
if (choice==1):
a.append(b)
elif (choice==2):
if (a==[]):
print("Queue Empty")
else:
a.pop(0)
elif (choice==3):
l=len(a)
for i in range(0,l):
print (a[i])
else:
print("wrong input")
c=input("Do you want to continue or not: ")
Program 43: Write a Program to show whether entered numbers are prime or not in the
given range.
Solution:
Solution:
t1 = tuple()
n = int (input("Total no of values in First tuple: "))
for i in range(n):
a = input("Enter Elements : ")
t1 = t1 + (a,)
t2 = tuple()
m = int (input("Total no of values in Second tuple: "))
for i in range(m):
a = input("Enter Elements : ")
t2 = t2 + (a,)
print("First Tuple : ")
print(t1)
print("Second Tuple : ")
print(t2)
t1,t2 = t2, t1
Solution:
def strep(str):
# convert string into list
str_lst =list(str)
# Iterate list
for i in range(len(str_lst)):
# Each Character Check with Vowels
if str_lst[i] in 'aeiouAEIOU':
# Replace ith position vowel with'*'
str_lst[i]='*'
#to join the characters into a new string.
new_str = "".join(str_lst)
return new_str
def main():
line = input("Enter string: ")
print("Orginal String")
print(line)
print("After replacing Vowels with '*'")
print(strep(line))
main()
Program 46: Read a text file and display the number of vowels/ consonants/ uppercase/
lowercase characters and other than character and digit in the file.
Solution:
filein = open("Mydoc1.txt",'r')
line = filein.read()
count_vow = 0
count_con = 0
count_low = 0
count_up = 0
count_digit = 0
count_other = 0
print(line)
for ch in line:
if ch.isupper():
count_up +=1
if ch.islower():
count_low += 1
if ch in 'aeiouAEIOU':
count_vow += 1
if ch.isalpha():
count_con += 1
if ch.isdigit():
count_digit += 1
if not ch.isalnum() and ch !=' ' and ch !='\n':
count_other += 1
print("Digits",count_digit)
print("Vowels: ",count_vow)
print("Consonants: ",count_con-count_vow)
print("Upper Case: ",count_up)
print("Lower Case: ",count_low)
print("other than letters and digit: ",count_other)
filein.close()
Program 47: Write a Python code to find the size of the file in bytes, the number of lines,
number of words and no. of character.
Solution:
import os
lines = 0
words = 0
letters = 0
filesize = 0
for line in open("Mydoc.txt"):
lines += 1
letters += len(line)
# get the size of file
filesize = os.path.getsize("Mydoc.txt")
Solution:
import pickle
def Writerecord(sroll,sname):
with open ('StudentRecord1.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname}
pickle.dump(srecord,Myfile)
def Readrecord():
with open ('StudentRecord1.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print()
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
Writerecord(sroll,sname)
def SearchRecord(roll):
with open ('StudentRecord1.dat','rb') as Myfile:
while True:
try:
rec=pickle.load(Myfile)
if rec['SROLL']==roll:
print("Roll NO:",rec['SROLL'])
print("Name:",rec['SNAME'])
except EOFError:
print("Record not find..............")
print("Try Again..............")
break
def main():
while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Search Records (By Roll No)')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r=int(input("Enter a Rollno to be Search: "))
SearchRecord(r)
else:
break
main()
Program 49: Create a binary file with roll number, name and marks. Input a roll number
and update details.
Solution:
def Writerecord(sroll,sname,sperc,sremark):
with open ('StudentRecord.dat','ab') as Myfile:
srecord={"SROLL":sroll,"SNAME":sname,"SPERC":sperc,
"SREMARKS":sremark}
pickle.dump(srecord,Myfile)
def Readrecord():
with open ('StudentRecord.dat','rb') as Myfile:
print("\n-------DISPALY STUDENTS DETAILS--------")
print("\nRoll No.",' ','Name','\t',end='')
print('Percetage',' ','Remarks')
while True:
try:
rec=pickle.load(Myfile)
print(' ',rec['SROLL'],'\t ' ,rec['SNAME'],'\t ',end='')
print(rec['SPERC'],'\t ',rec['SREMARKS'])
except EOFError:
break
def Input():
n=int(input("How many records you want to create :"))
for ctr in range(n):
sroll=int(input("Enter Roll No: "))
sname=input("Enter Name: ")
sperc=float(input("Enter Percentage: "))
sremark=input("Enter Remark: ")
Writerecord(sroll,sname,sperc,sremark)
def Modify(roll):
with open ('StudentRecord.dat','rb') as Myfile:
newRecord=[]
while True:
try:
rec=pickle.load(Myfile)
newRecord.append(rec)
except EOFError:
break
found=1
for i in range(len(newRecord)):
if newRecord[i]['SROLL']==roll:
name=input("Enter Name: ")
perc=float(input("Enter Percentage: "))
remark=input("Enter Remark: ")
newRecord[i]['SNAME']=name
newRecord[i]['SPERC']=perc
newRecord[i]['SREMARKS']=remark
found =1
else:
found=0
if found==0:
print("Record not found")
with open ('StudentRecord.dat','wb') as Myfile:
for j in newRecord:
pickle.dump(j,Myfile)
def main():
while True:
print('\nYour Choices are: ')
print('1.Insert Records')
print('2.Dispaly Records')
print('3.Update Records')
print('0.Exit (Enter 0 to exit)')
ch=int(input('Enter Your Choice: '))
if ch==1:
Input()
elif ch==2:
Readrecord()
elif ch==3:
r =int(input("Enter a Rollno to be update: "))
Modify(r)
else:
break
main()
Program 50: Write a program to create a library in python and import it in a program.
Solution:
import math
def rectangle(s1,s2):
area = s1*s2
return area
def circle(r):
area= math.pi*r*r
return area
def square(s1):
area = s1*s1
return area
def triangle(s1,s2):
area=0.5*s1*s2
return area
# Calculator.py Module
def sum(n1,n2):
s = n1 + n2
return s
def sub(n1,n2):
r = n1 - n2
return r
def mult(n1,n2):
m = n1*n1
return m
def div(n1,n2):
d=n1/n2
return d
# main() function
from Mypackage import Area
from Mypackage import Calculator
def main():