0% found this document useful (0 votes)
66 views

Practical Programs - 24-25-1

Uploaded by

ashika2731
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Practical Programs - 24-25-1

Uploaded by

ashika2731
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

1 1.

PALINDROME
Aim: Write a program to show entered string is a palindrome or not.
str=input("enter the string")
l=len(str)
p=l-1
index=0
while(index<p):
if(str[index]==str[p]):
index=index+1
p=p-1
else:
print("string is not a palindrome")
break
else:
print("string is palindrome")

Output:

2 2. STATUS OF A STRING
Aim: WAP to counts the number of alphabets ,digits, uppercase,
lowercase, # spaces and other characters(status of a string).
str1 =input("enter a string")
n=c=d=s=u=l=o=0
for ch in str1:
if ch.isalnum():
n+=1
if ch.isupper():
u=u+1
elif ch.islower():
l=l+1
elif ch.isalpha():
c=c+1
elif ch.isdigit():
d=d+1
elif ch.isspace():
s=s+1
else:
o=o+1
print("No.of alpha and digit",n)
print("No.of capital alpha",u)
print("No.of smallalphabet",l)
print("No.of digit",d)
print("No. of spaces",s)
print("No of other character",o)

3 3. LIST MANIPULATION
Aim: WAP to remove all odd numbers from the given list.
Program 3:WAP to remove all odd numbers from the given list.
L=[2,7,12,5,10,15,23]
for i in L:
if i%2==0:
L.remove(i)
print(L)
Output:

4 4. FREQUENCY – LIST ELEMENTS


Aim: WAP to display frequencies of all the element of a list.

L=[3,21,5,6,3,8,21,6]
L1=[]
L2=[]
for i in L:
if i not in L2:
x=L.count(i)
L1.append(x)
L2.append(i)
print('element','\t',"frequency")
for i in range (len(L1)):
print(L2[i],'\t\t',L1[i])
Output:

5 5. EXTRACTION – LIST ELEMENTS


Aim: Write a program to display those string which are starting with ‘A’ from
the given list.
L=['AUSHIM','LEENA','AKHTAR','HIBA','NISHANT','AMAR']
count=0
for i in L:
if i[0] in ('aA'):
count=count+1
print(i)
print("appearing",count,"times")

Output:

6 6. SUM OF VALUES - LIST


Aim: Write a program to find and display the sum of all the values which are
ending with 3 from a list.

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

7 7. SWAPPING – LIST ELEMENTS


Aim: Write a program to swap the content with next value, if it is divisible by
7 so that the resultant array will look like : 3,5,21,6,8,14,3,14.
num=[3,21,5,6,14,8,14,3]
l=len(num)
i=0
print('The elements of the list is ',num)
while i<8:
if num[i]%7==0:
num[i],num[i+1]=num[i+1],num[i]
i=i+2
else:
i=i+1
print('The elements of the list after swapping is ', num)

8 8. TUPLE - CREATION
Aim: Write a program to accept values from a user and create a tuple.
t=tuple()
n=int(input("enter limit:"))
for i in range(n):
a=input("enter number:")
t=t+(a,)
print("output is")
print(t)
Output:

9 9. COUNTRY & CAPITAL – SEARCHING - DICTIONARY


Write a program to input name of ‘n’ countries and their capital and currency
store, it in a dictionary and display in tabular form also search and display for
a particular country.
d1=dict()
i=1
n=int(input("Enter number of entries"))
while i<=n:
c=input("Enter country:")
cap=input("Enter capital:")
curr=input("Enter currency of country")
d1[c]=[cap,curr]
i=i+1
l=d1.keys()
print("\ncountry\t\t","capital\t\t","currency")
for i in l:
z=d1[i]
print(i,'\t\t',end=" ")
for j in z:
print(j,'\t',end='\t')
print()
x=input("\nEnter country to be searched:") #searching
for i in l:
if i==x:
print("\nCountry\t","Capital\t","Currency\t")
z=d1[i]
print(i,'\t',end=" ")
for j in z:
print(j,'\t',end=" ")

10 10. FACTORIAL - FUNCTION


Write a program to calculate the factorial of the entered number using the
function fact(n). Accept n from the user.
def fact(n):
f=1
for i in range(1,a+1):
f *=i
print(a, " factorial:",f)
a=int(input("Enter the number"))
fact(a)

11 11. MENU DRIVEN – NUMBERS - FUNCTION


Aim: Write a menu driven program to accept a number from user and check
it is a Disarium number or a Special number
Disarium number:
A number is said to be the Disarium number when the sum of its digit raised
to the power of their respective positions becomes equal to the number itself.
For example, 175 is a Disarium number as follows:
11+ 72 + 53 = 1+ 49 + 125 = 175
Special number:
Special number is a integer number which where addition of sum of digit and
product of digits are same to number.
Example:
29:
2 + 9 = 11
2 x 9 = 18
11 + 18 = 29
Program:
def calculateLength(n):
length = 0
while n>0:
length = length + 1;
n = n//10;
return length;
def disarium(n):
l = calculateLength(n);
rem = sum = 0;
while(n > 0):
rem = n%10;
sum = sum + int(rem**l);
n = n//10;
l = l - 1;
return sum

def special(n):
b=0
c=1
t=a
while a>0:
d = a%10
b +=d
c *=d
a //=10
if b+c==t:
print('Speical number')
else:
print('Not a special number')
def main():
print('Menu....')
print('1. Disarium Number')
print('2. Special Number')
ch=int(input('Press 1 or 2..'))
n=int(input('Enter number'))
if ch==1:
a=disarium(n)
if a == n:
print(str(n) + " is a disarium number");
else:
print(str(n) + " is not a disarium number");
elif ch==2:
special(n)
else:
return
Output:

12 12. FIBONACCI & TRIBONACCI SERIES - FUNCTION


Write a menu driven program to generate Fibonacci series and Tribonacci
series .
Program:
#fibonacci series
def fib(n):
f1,f2=-1,1
for i in range(n):
f3=f1+f2
print(f3,end=' ')
f1=f2
f2=f3
def tri(n):
f1=-1
f2=0
f3=1
for i in range(10):
f4=f1+f2+f3
f1=f2
f2=f3
f3=f4
print(f4,end=' ')
def main():
print('Menu...')
print('1. Fibonacci Series \n2. Tribonacci Series')
while True:
ch=input('\nEnter choice')
if ch=='1':
n=int(input('Enter number of terms'))
fib(n)
elif ch=='2':
n=int(input('Enter number of terms'))
tri(n)
else:
break

13 13. PRIME NUMBER - FUNCTION


Write a program to show all non -prime numbers in the entered range
Program:
def nprime(lower,upper):
print("”ALL NUMBERS EXCEPT PRIME NUMBERS WITHIN THE RANGE”")
for i in range(lower, upper+1):
for j in range(2, i):
ans = i % j
if ans==0:
print (i,end=' ')
break

l=int(input('Enter lower range'))


u=int(input('Enter upper range'))
nprime(l,u)
Output:

14 14. COUNTING -TEXT FILE


Aim: Write a program to show and count the number of words in a text file
‘DATA.TXT’ which is starting/ended with a word ‘The’, ‘the’.
Program:
f1=open("DATA.TXT ","r")
s=f1.read()
print("All Data of file in string : \n",s)
print("="*70)
count=0
words=s.split()
print("All Words: ",words,"\n length is ",len(words))
for word in words:
if word.startswith("the")==True: # word.ends with(“the”)
count+=1
print("Words start with 'the' is ",count)

15 15. COUNTING VOWELS & CONSONANTS – TEXT FILE


Aim: Write a program to read data from a text file DATA.TXT, and display
each words with number of vowels and consonants.
Program:
f1=open("happy.txt","r")
s=f1.read()
print(s)
countV=0
countC=0
words=s.split()
print(words,"\n No.of words ",len(words))
for word in words:
countV=0
countC=0
for ch in word:
if ch.isalpha()==True:
if ch in 'aeiouAEIOU':
countV+=1
else:
countC+=1
print("Word : ",word,", V: ",countV,", C= ", countC)
16 16. SHORTEST & LONGEST WORD – TEXT FILE
Aim: Write a program to read data from a text file DATA.TXT, and display
word which have maximum/minimum characters.
Program:

f1=open("happy.txt","r")
s=f1.read()
print(s)
words=s.split()
print(words,", ",len(words))
maxC=len(words[0])
minC=len(words[0])
minfinal=""
maxfinal=""
for word in words[1:]:
length=len(word)
if maxC<length:
maxC=length
maxfinal=word
if minC>length:
minC=length
minfinal=word
print("Max word : ",maxfinal,", maxC: ",maxC)
print("Min word : ",minfinal,", minC: ",minC)

17 17. COUNTING CHARACTERS – BINARY FILE


Aim: Write a program to write a string in the binary file “comp.dat” and count
the number of times a character appears in the given string using a
dictionary.
import pickle
str="MALAYALAM"
f1=open('comp.dat','wb')
pickle.dump(str,f1)
print("File Created")
f1.close()
f1=open('comp.dat','rb')
str=pickle.load(f1)
print("\nThe string in the binary file is : \n",str)
d={}
for x in str:
if x not in d:
d[x]=1
else:
d[x]=d[x]+1
print("\nThe occurrences of each letter of string is :\n", d)
f1.close()

18 18. STRING MANIPULATION – BINARY FILE


Aim: Write a program that will write a string in binary file "school.dat" and
display the words of the string in reverse order.
import pickle
str="No one can make you feel inferior without your consent"
f1=open('school.dat','wb')
pickle.dump(str,f1)
print("The string is written in the ",f1.name, "file")
f1.close()
f1=open('school.dat','rb')
str1=pickle.load(f1)
print("\nThe string in the binary file is : \n",str1)
str1=str1.split(" ")
l=list(str1)
print("The list is \n",l)
l.reverse()
print("The reverse is \n",l)
f1.close()
Output:

19 19. EMPLOYEE DETAILS – BINARY


Aim: Write a Python program for the following specifications.
Consider a binary file “Emp.dat” containing details such as empno, ename,
salary .Write a python program to display details of those employees who are
earning between 20000 and 40000.
Program:
import pickle
fout=open('emp.dat','ab+')
d={}
while True:
d['rollno']=input('Enter emp number')
d['name']=input('Enter name')
d['sal']=int(input('Enter salary'))
pickle.dump(d,fout)
ch=input('continue....')
if ch !='y':
break
fout.seek(0)
try:
x=pickle.load(fout)
while x:
if x['sal']>20000 and x['sal']<50000:
print(x)
x=pickle.load(fout)
except:
print('End of file')
fout.close()
Output:
20 A binary file named ‘TEST.DAT’ has some records of the structure [tesid,
subject, maxmarks, scoremarks]

Write a function in python named dispavg(sub) that will accept a subject as


argument and read the contents of TEST.DAT. The function will calculate &
display the scoremarks of the passed subject on screen.

def create():
f = open("test.dat", "wb+")
for i in range(5):
tid=input('Enter testid')
sub = input('Enter the subject')
maxmarks=int(input('Ener max marks'))
score = int(input('Enter marks scored'))
pickle.dump([tid, sub, maxmarks,score],f)
f.close()
def dispavg():
f = open("test.dat", "rb")
c=0
s=0
sub=input('Enter the subject')
try:
while True:
g = pickle.load(f)
print(g)
if g[1]==sub:
s=s+g[3]
c=c+1
except:
f.close()
print('Average marks...',s/c)
Output:
21 20. READING & WRITING – CSV FILE
Aim: Write a program to insert list data in CSV File and print it.
import csv
fields = ['Name', 'Branch', 'Year', 'CGPA']
# data rows of csv file
rows = [ ['Nikhil', 'COE', '2', '9.0'],
['Sanchit', 'COE', '2', '9.1'],
['Aditya', 'IT', '2', '9.3'],
['Sagar', 'SE', '1', '9.5'],
['Prateek', 'MCE', '3', '7.8'],
['Sahil', 'EP', '2', '9.1']]
filename = "MYCSV.csv"
with open(filename, 'w',newline='') as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerow(fields)
csvwriter.writerows(rows)
with open('MYCSV.csv') as File:
reader = csv.reader(File)
for row in reader:
print(row)
Output:
22 A CSV file student.csv has following contents:
Rno,Name,Score,Class
101,Alex,80,12
102,Monica,84,12
103,Ajay,72,12
104,Irfan,82,11
Write a function count_rec() that count and display number of records where
score is more than 80.

Solution

import csv

def count_rec():
file = open("student.csv","r")
count = 0
creader = csv.reader(file)
next(creader)
for row in creader:
if int(row[2])>80:
count += 1
print("Number of records are",count)
file.close()

count_rec()

Output

Number of records are 2

23 A CSV file result.csv has following contents:


Rno,Name,P,C,M
101,Alex,78,55,89
102,Monica,65,67,71
103,Ajay,77,87,79
104,Irfan,90,89,92
Write a function make_copy() that creates a new CSV file copy.csv containing
all records of result.csv after adding the marks of PCM. The file copy.csv
contents should be like:

Rno,Name,Total
101,Alex,222
102,Monica,203
103,Ajay,243
104,Irfan,271

Solution

import csv

def make_copy():
infile = open("result.csv","r")
outfile = open("copy.csv","w",newline="")
creader = csv.reader(infile)
cwriter = csv.writer(outfile)
next(creader)
cwriter.writerow(['Rno','Name','Total'])
for row in creader:
sum = int(row[2])+int(row[3])+int(row[4])
cwriter.writerow([row[0],row[1],sum])
infile.close()
outfile.close()

make_copy()

Output:
INPUT FILE:

OUTPUT FILE:
24 Write a program to create a CSV File 'Student.csv' (content shown below).
Content of CSV file is input by user.

Rollno,Name,Class
1,Sakham,XII
2,Nisha,XII
3,Irfan,XII
4,Vaani,XII
5,Jasvinder,XII

Solution

import csv
file = open('student.csv', 'w', newline='')
mywriter = csv.writer(file)
data = [ ]
header = ['Rollno', 'Name', 'Class']
data.append(header)
for i in range(5):
rollno = int(input("Enter Roll Number : "))
name = input("Enter Name : ")
Class = input("Enter Class : ")
rec = [rollno,name,Class]
data.append(rec)
mywriter.writerow(data)
file.close()

Output

Enter Roll Number : 1


Enter Name : Sakham
Enter Class : XII
Enter Roll Number : 2
Enter Name : Nisha
Enter Class : XII
Enter Roll Number : 3
Enter Name : Irfan
Enter Class : XII
Enter Roll Number : 4
Enter Name : Vaani
Enter Class : XII
Enter Roll Number : 5
Enter Name : Jasvinder
Enter Class : XII
25 25. STACK – DATA STRUCTURE
Write a program to show push and pop operation using stack.

def push(stack,x):
stack.append(x)
def pop(stack):
n = len(stack)
if(n<=0):
print("Stack empty....Pop not possible")
else:
stack.pop()
def display(stack):
if len(stack)<=0:
print("Stack empty...........Nothing to display")
return
for i in stack:
print(i,end=" ")
#main program starts from here
x=[]
choice=0
while (choice!=4):
print("\n********Stack Menu***********")
print("1. push(INSERT)")
print("2. pop(DELETE)")
print("3. Display ")
print("4. Exit")
choice = int(input("Enter your choice :"))
if(choice==1):
value = int(input("Enter value "))
push(x,value)
if(choice==2):
pop(x)
if(choice==3):
display(x)
if(choice==4):
print("You selected to close this program")

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy