List of Programs for Python
List of Programs for Python
Practical file - XI
DOWNLOAD
Marks Grade
>=90 A
75-90 B
60-75 C
Below 60 D
35. Write a Python script that displays the first ten Mersenne
numbers.
36. Write a Python script that displays the first ten Mersenne
numbers and displays ‘Prime’ next to Mersenne Prime
Numbers.
37. Write a program to calculate BMI and print the nutritional
status as per the following table:
cut-off
Underweight <18.5
Normal 18.5-24.9
Overweight 25-29.9
Obese ≥30
1 3
1 3 5
1 3 5 7
40. Write a python script to input two numbers and print their
LCM and HCF.
S=(1)+(1+2)+(1+2+3)+……+(1+2+3+….+n)
42. Write a program to print the following using a single loop
(no nested loops)
1 1
1 1 1
1 1 1 1
1 1 1 1 1
4321
432
43
44. A program that reads a line and prints its statistics like:
51. WAP to remove all odd numbers from the given list.
54. WAP in Python to find and display the sum of all the values
which are ending with 3 from a list.
Solutions:
Download
Sum=a+b
Download
Download
#Write a program that accepts base and height and
calculate the area of triangle
Area=(1/2)*b*h
Download
P=(a+b+c)/3
print('The percentage marks are:', P,'%')
Download
Download
SI=(P*R*T)/100
Download
Q=a//b
R=a%b
Download
Download
Download
print('Rectangle Specifications')
print('Length=',l)
print('Breadth=', b)
print('Area=', area)
Download
13. Write a program that reads the number n and prints the
value of n², n³ and n⁴.
Download
Download
Download
Feet=a*0.032
Inch=a*0.393
16. Write a program that accepts the age and print if one is
eligible to vote or not.
Download
Download
# Write a program that accepts two numbers and
# check if the first number is fully divisible by
second number or not.
Download
Area=b*h
Perimeter=2*(b+w)
Download
# Write a program to accept the year and
# check if it is a leap year or not.
Download
import math
print('To calculate 4x⁴+3y³+9z+6π')
x=float(input('Enter the number x:'))
y=float(input('Enter the number y:'))
z=float(input('Enter the number z:'))
b=(4*math.pow(x,4))+(3*math.pow(y,3))+(9*z)
+(6*math.pi)
print('The result of the above expression is:',b)
Download
import math
x=float(input('Enter the number:'))
a=math.pow(x,2)
b=math.sqrt(x)
if x%2!=0:
print('The value of square is:',a)
else:
print('The value of square root is:',b)
Download
if a>=0:
if a==0:
print('The number is zero')
else:
print('The number is a positive number')
else:
print('The number is a negative number')
Download
'''
Write a program to input percentage marks of a
student and find the grade as per following
criterion:
Marks Grade
>=90 A
75-90 B
60-75 C
Below 60 D
'''
a=float(input('Enter the percentage marks:'))
if a>=90:
print('The student has got an A grade')
elif a>=75 and a<90:
print('The student has got a B grade')
elif a>=60 and a<75:
print('The student has got a C grade')
else:
print('The student has got a D grade')
Download
Download
# Write a program to display a menu for calculating
# area of circle or perimeter of the circle.
Download
Download
Download
Download
Download
num=int(input('Enter a number:'))
fact=1
a=1
while a<=num:
fact*=a
a+=1
print('The factorial of',num,'is',fact)
Download
for i in range(1,6):
print()
for j in range(1,i):
print('*',end=' ')
Download
# Write a Python script to print Fibonacci series’
first 10 elements.
first=0
second=1
print(first, end=' ')
print(second,end=' ')
for a in range(1,9):
third=first+second
print(third,end=' ')
first,second=second,third
Download
Download
if angle1+angle2+angle3==180:
print('The angles form a triangle')
else:
print('The angles do not form a triangle')
35. Write a Python script that displays the first ten Mersenne
numbers.
Download
36. Write a Python script that displays the first ten Mersenne
numbers and displays ‘Prime’ next to Mersenne Prime
Numbers.
Download
Download
'''
1 3
1 3 5
1 3 5 7
Download
Download
Download
40. Write a python script to input two numbers and print their
LCM and HCF.
S=(1)+(1+2)+(1+2+3)+……+(1+2+3+….+n)
Download
Sum=0
n=int(input('How many terms?'))
for a in range(2,n+2):
term=0
for b in range(1,a):
term+=b
print('Term',(a-1),':',term)
Sum+=term
print('Sum of',n,'terms is:',Sum)
1 1
1 1 1
1 1 1 1
1 1 1 1 1
Download
'''
42.Write a program to print the following using a
single loop (no nested loops)
1
11
111
1111
11111
'''
n=1
for a in range(5):
print(n,end = ' ')
print()
n=n*10+1
Download
4321
432
43
'''
for i in range(4):
for j in range(4,i,-1):
print(j,end=' ')
else:
print()
44. A program that reads a line and prints its statistics like:
line=input('Enter a line:')
lowercount=uppercount=0
digitcount=alphacount=0
for a in line:
if a.islower():
lowercount+=1
elif a.isupper():
uppercount+=1
elif a.isdigit():
digitcount+=1
if a.isalpha():
alphacount+=1
Download
#Write a program that reads a line and a substring
#and displays the number of occurrences of the given
substring in the line.
line=input('Enter line:')
sub=input('Enter substring:')
length=len(line)
lensub=len(sub)
start=count=0
end=length
while True:
pos=line.find(sub,start,end)
if pos!=-1:
count+=1
start=pos+lensub
else:
break
if start>=length:
break
print('No. of occurences of',sub,':',count)
Download
string=input('Enter a string:')
length=len(string)
a=0
end=length
string2=''
while a<length:
if a==0:
string2+=string[0].upper()
a+=1
elif(string[a]==' ' and string[a+1]!=' '):
string2+=string[a]
string2+=string[a+1].upper()
a+=2
elif (string[a]==',' and string[a+1]!=','):
string2+=string[a]
string2+=string[a+1].upper()
a+=2
else:
string2+=string[a]
a+=1
print('Original string:',string)
print('Capitalized words string:',string2)
Download
string=input('Enter a string:')
length=len(string)
mid=length//2
rev=-1
for a in range(mid):
if string[a]==string[rev]:
print(string,'is a palindrome.')
break
else:
print(stri
Download
string=input('Enter a string:')
length=len(string)
maxlength=0
maxsub=''
sub=''
lensub=0
for a in range(length):
if string[a] in 'aeiou' or string[a] in 'AEIOU':
if lensub>maxlength:
maxsub=sub
maxlength=lensub
sub=''
lensub=0
else:
sub+=string[a]
lensub=len(sub)
a+=1
print('Maximum length consonant substring
is:',maxsub,end=' ')
print('with',maxlength,'characters')
49. Write a program that reads a string and then prints a
string that capitalizes every other letter in the string.
Download
string=input('Enter a string:')
length=len(string)
print('Original string:',string)
string2=''
for a in range(0,length,2):
string2+=string[a]
if a<length-1:
string2+=string[a+1].upper()
print('Alternatively capitalized string:',string2)
Download
if sub==domain:
if ledo!=lema:
print('It is valid email id')
else:
print('This is invalid email id- contains
just the domain name')
else:
print('This email-d is either not valid or
belongs to some other domain')
51. WAP to remove all odd numbers from the given list.
Download
Download
Download
for i in L:
if i not in L2:
x=L.count(i)
L1.append(x)
L2.append(i)
for i in range(len(L1)):
print (L2[i],'\t\t\t',L1[i])
54. WAP in Python to find and display the sum of all the values
which are ending with 3 from a list.
Download
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 (s
Download
if flag==1:
print("Element found")
else:
print("Elemnet not found")
Download
Download
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
Download
Download
Download
#create a tuple
tuplex =
"l","e","a","r","n","p","y","t","h","o","n","4","c","
b","s","e"
print("Tuple Before Removing an item")
print(tuplex)
#converting the tuple to list
listx = list(tuplex)
#use different ways to remove an item of the list
listx.remove("4")
#converting the tuple to list
tuplex = tuple(listx)
print("\nTuple After Removing an item '4'")
print(tuplex)
Download
Download
Download
string=input('Enter a string:')
length=len(string)
mid=length//2
rev=-1
for a in range(mid):
if string[a]==string[rev]:
print(string,'is a palindrome.')
break
else:
print(string,'is not a palindrome.')
Download
Download
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
Download
record = dict ()
i=1
n= int (input ("How many records u want to enter: "))
while(i<=n):
Adm = input("Enter Admission number: ")
roll = input("Enter Roll Number: ")
name = input("Enter Name :")
perc = float(input("Enter Percentage : "))
t = (roll,name, perc)
record[Adm] = t
i = i + 1
Nkey = record.keys()
for i in Nkey:
print("\nAdmno- ", i, " :")
r = record[i]
print("Roll No\t", "Name\t", "Percentage\t")
for j in r:
print(j, end = "\t")
Download
def strep(str):
str_lst =list(str)
# Iterate list
for i in range(len(str_lst)):
if str_lst[i] in 'aeiouAEIOU':
str_lst[i]='*'
def main():
line = input("Enter string: ")
print("Orginal String")
print(line)
print("After replacing Vowels with '*'")
print(strep(line))
main()
Download
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
def main():
n = int(input("Enter any number: "))
print("The factorial of given number is:
",factorial(n))
main()
Download
def lstSum(lst,n):
if n==0:
return 0
else:
return lst[n-1]+lstSum(lst,n-1)
Download
def fibonacci(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return(fibonacci(n-2) + fibonacci(n-1))
Download
filein = open("Mydoc.txt",'r')
line =" "
while line:
line = filein.readline()
#print(line)
for w in line:
if w == ' ':
print('#',end = '')
else:
print(w,end = '')
filein.close()
'''
#-------------OR------------------
filein = open("Mydoc.txt",'r')
for line in filein:
word= line .split()
for w in word:
print(w + '#',end ='')
print()
filein.close()
'''
11. Read a text file and display the number of vowels/
consonants/ uppercase/ lowercase characters and other than
character and digit in the file.
Download
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()
12. Write a Python code to find the size of the file in bytes, the
number of lines, number of words and no. of character.
Download
import os
lines = 0
words = 0
letters = 0
filesize = 0
Download
def get_longest_line(filename):
large_line = ''
large_line_len = 0
return large_line
14. Create a binary file with the name and roll number. Search
for a given roll number and display the name, if not found
display appropriate message.
Download
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()
15. Create a binary file with roll number, name and marks.
Input a roll number and update details.
Download
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:
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()
16. Remove all the lines that contain the character `a' in a file
and write it to another file
Download
f1 = open("Mydoc.txt")
f2 = open("copyMydoc.txt","w")
for line in f1:
if 'a' not in line:
f2.write(line)
print('## File Copied Successfully! ##')
f1.close()
f2.close()
f2 = open("copyMydoc.txt","r")
print(f2.read())
Download
import csv
with open('Student_Details.csv','w',newline='') as
csvf:
writecsv=csv.writer(csvf,delimiter=',')
choice='y'
while choice.lower()=='y':
rl=int(input("Enter Roll No.: "))
n=input("Enter Name: ")
p=float(input("Enter Percentage: "))
r=input("Enter Remarks: ")
writecsv.writerow([rl,n,p,r])
print(" Data saved in Student Details
file..")
choice=input("Want add more
record(y/n).....")
with open('Student_Details.csv','r',newline='') as
fileobject:
readcsv=csv.reader(fileobject)
for i in readcsv:
print(i)
Download
import csv
with open('Student_Details.csv') as f:
csv_file = csv.reader(f, delimiter=",")
#loop through csv list
for row in csv_file:
else:
print("Record Not found")
Download
import random
import random
def roll_dice():
print (random.randint(1, 6))
flag = True
while flag:
user_prompt = input(">")
if user_prompt.lower() == "quit":
flag = False
else:
print("Rolling dice...\nYour number is:")
roll_dice()
Download
# Area.py Module
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
def main():
print("\nThe Sum is :
",Calculator.sum(num1,num2))
print("\nThe Multiplication is :
",Calculator.mult(num1,num2))
print("\nThe sub is :
",Calculator.sub(num1,num2))
print("\nThe Division is :
",Calculator.div(num1,num2))
main()
Download
def Insertion_Sort(nlist):
for index in range(1,len(nlist)):
currentvalue = nlist[index]
position = index
nlist[position]=currentvalue
# DRIVER CODE
def main():
print ("SORT MENU")
print ("1. BUBBLE SORT")
print ("2. INSERTION SORT")
print ("3. EXIT")
choice=int(input("Enter your Choice [ 1 - 3 ]:
"))
nlist = [14,46,43,27,57,41,45,21,70]
if choice==1:
print("Before Sorting: ",nlist)
Bubble_Sort(nlist)
print("After Bubble Sort: ",nlist)
elif choice==2:
print("Before Sorting: ",nlist)
Insertion_Sort(nlist)
print("After Insertion Sort: ",nlist)
else:
print("Quitting.....!")
main()
22. Take a sample of ten phishing e-mails (or any text file) and
find the most commonly occurring word(s).
Download
def Read_Email_File():
import collections
fin = open('email.txt','r')
a= fin.read()
d={ }
L=a.lower().split()
for word in L:
word = word.replace(".","")
word = word.replace(",","")
word = word.replace(":","")
word = word.replace("\"","")
word = word.replace("!","")
word = word.replace("&","")
word = word.replace("*","")
for k in L:
key=k
if key not in d:
count=L.count(key)
d[key]=count
n = int(input("How many most common words to
print: "))
print("\nOK. The {} most common words are as
follows\n".format(n))
word_counter = collections.Counter(d)
for word, count in word_counter.most_common(n):
print(word, ": ", count)
fin.close()
#Driver Code
def main():
Read_Email_File()
main()
Download
def isempty(stk):
if stk==[]:
return True
else:
return False
def push(stk,item):
stk.append(item)
top=len(stk)-1
def pop(stk):
if isempty(stk):
return "underflow"
else:
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)-1
return item
def peek(stk):
if isempty(stk):
return "underflow"
else:
top=len(stk)-1
return stk[top]
def display(stk):
if isempty(stk):
print('stack is empty')
else:
top=len(stk)-1
print(stk[top],'<-top')
for i in range(top-1,-1,-1):
print(stk[i])
#Driver Code
def main():
stk=[]
top=None
while True:
print('''stack operation
1.push
2.pop
3.peek
4.display
5.exit''')
choice=int (input('enter choice:'))
if choice==1:
item=int(input('enter item:'))
push(stk,item)
elif choice==2:
item=pop(stk)
if item=="underflow":
print('stack is underflow')
else:
print('poped')
elif choice==3:
item=peek(stk)
if item=="underflow":
print('stack is underflow')
else:
print('top most item is:',item)
elif choice==4:
display(stk)
elif choice==5:
break
else:
print('invalid')
exit()
main()
Download
# Driver function
def main():
qList = []
front = rear = 0
while True:
print()
print("##### QUEUE OPERATION #####")
print("1. ENQUEUE ")
print("2. DEQUEUE ")
print("3. PEEK ")
print("4. DISPLAY ")
print("0. EXIT ")
choice = int(input("Enter Your Choice: "))
if choice == 1:
ele = int(input("Enter element to
insert"))
Enqueue(qList,ele)
elif choice == 2:
val = Dqueue(qList)
if val == "UnderFlow":
print("Queue is Empty")
else:
print("\n Deleted Element was :
",val)
elif choice==3:
val = Peek(qList)
if val == "UnderFlow":
print("Queue is Empty")
else:
print("Item at Front: ",val)
elif choice==4:
Display(qList)
elif choice==0:
print("Good Luck......")
break
main()
Download
def binary_Search(Lst,num):
start = 0
end = len(Lst) - 1
mid = (start + end) // 2
found = False
position = -1
while start <= end:
if Lst[mid] == num:
found = True
position = mid
print('Number %d found at position %d'%
(num, position+1))
break
if found==False:
print('Number %d not found' %num)
# DRIVER CODE
def main():
print ("SEARCH MENU")
print ("1. LINEAR SERACH")
print ("2. BINARY SEARCH")
print ("3. EXIT")
choice=int(input("Enter your Choice [ 1 - 3 ]:
"))
arr = [12, 34, 54, 2, 3]
n = len(arr)
if choice==1:
print("The List contains : ",arr)
num=int(input("Enter number to be searched:
"))
index = Linear_Search(arr,num)
if choice==2:
arr = [2, 3,12,34,54] #Sorted Array
print("The List contains : ",arr)
num=int(input("Enter number to be searched:
"))
result = binary_Search(arr,num)
main()