You are on page 1of 22

PYTHON LAB MANUAL

1.write a program to sum all the elements from n1 to n2 where n1 and n2 are
positive integers.
n1=int(input('enter the first number:'))

n2=int(input('enter the second number:'))

if n1>n2:

t=n1

n1=n2

n2=t

sum=0

for i in range(n1,n2+1):

sum+=i

print('sum of the numbers between',n1,'and',n2,'is=',sum)

Output:
enter the first number:1

enter the second number:10

sum of the numbers between 1 and 10 is= 55.

2.Input an array of n numbers and find separate the sum of positive numbers
and negative numbers.
n=int(input('enter the no of items in the list:'))

nums=[]

print('enter {0:2d} numbers'.format(n))

for i in range(n):

nums.append(int(input()))

nc=0

pc=0

zc=0

sump=0
PYTHON LAB MANUAL

sumn=0

for elt in nums:

if elt==0:

zc+=1

elif elt<0:

nc+=1

sumn+=elt

else:

pc+=1

sump+=elt

print('no of zeros is:',zc)

print('no of negative nos is:',nc)

print('no of positive nos is:',pc)

print('sum of positive numbers is:',sump)

print('sum of negative numbers is:',sumn)

Output:
enter the no of items in the list:4

enter 4 numbers

-8

no of zeros is: 1

no of negative nos is: 1

no of positive nos is: 2

sum of positive numbers is: 8

sum of negative numbers is: -8


PYTHON LAB MANUAL

3.Write a program to search an element using linear search.


n=int(input('enter size of the list:'))

nums=[]

print('enter {0:2d} numbers'.format(n))

for i in range(n):

nums.append(int(input()))

elt=int(input('enter the searching element:'))

found=False

for i in range(n):

if elt==nums[i]:

found=True

pos=i+1

break

if found:

print('{0} is found at position {1}'.format(elt,pos))

else:

print('{0} is not found in the list'.format(elt))

Output:
enter size of the list:4

enter 4 numbers

enter the searching element:2

2 is found at position 4
PYTHON LAB MANUAL

4.write a program to search an element using binary search.


def bsearch(elt,a,low,high):

if high<low:

return -1

mid=(low+high)//2

if elt==a[mid]:

return mid+1

elif elt<a[mid]:

return bsearch(elt,a,low,mid-1)

else:

return bsearch(elt,a,mid+1,high)

n=int(input('enter size of the list:'))

a=[]

print('enter {0:2d} numbers'.format(n))

for i in range(n):

a.append(int(input()))

elt=int(input('enter the searching element:'))

a.sort()

print('the original sorted list is:')

for i in a:

print(i)

print(a)

p=bsearch(elt,a,0,n-1)

if p<0:

print('{0} is not in position'.format(p))

else:
PYTHON LAB MANUAL

print('{0} is found at position {1}'.format(elt,p))

Output:
enter size of the list:4

enter 4 numbers

enter the searching element:6

the original sorted list is:

[2, 3, 6, 8]

[2, 3, 6, 8]

[2, 3, 6, 8]

[2, 3, 6, 8]

6 is found at position 3.

5.write a program to stimulate stack.


class stack:

def __init__(self):

self.top=-1

self.st=[]

def readsize(self):

self.n=int(input('enter size of stack'))


PYTHON LAB MANUAL

def push(self):

if self.top==self.n-1:

print('stack is full')

else:

el=int(input('enter elements to be pushed'))

self.st.append(el)

self.top+=1

print(el,'is pushed into stack')

def pop(self):

if self.top==-1:

print('stack is empty')

else:

el=self.st[self.top]

print('deleted element is',el)

del self.st[self.top]

self.top-=1

def display(self):

if self.top==-1:

print('stack is empty')

else:

print('element of stack is\n')

for i in range(self.top,-1,-1):

print(self.st[i],'')

s=stack()

s.readsize()

while True:
PYTHON LAB MANUAL

print('1.push\n 2.pop\n 3.display\n 4.exit\n')

ch=int(input('enter your choice'))

if ch==1:

s.push()

elif ch==2:

s.pop()

elif ch==3:

s.display()

else:

break.

Output:
enter size of stack:4

1.push

2.pop

3.display

4.exit

enter your choice:1

enter elements to be pushed:2

2 is pushed into stack:

1.push

2.pop

3.display

4.exit

enter your choice:1

enter elements to be pushed:4

4 is pushed into stack:


PYTHON LAB MANUAL

1.push

2.pop

3.display

4.exit

enter your choice:1

enter elements to be pushed:6

6 is pushed into stack:

1.push

2.pop

3.display

4.exit

enter your choice:3

element of stack is

1.push

2.pop

3.display

4.exit

enter your choice:2

deleted element is: 6

1.push

2.pop

3.display

4.exit
PYTHON LAB MANUAL

enter your choice:2

deleted element is: 4

1.push

2.pop

3.display

4.exit

enter your choice:3

element of stack is

2.

6.Using a stack evaluate an arithmetic expression.


def postevaluation(str):

strlist=str.split()

n=len(strlist)

st=[]

for i in range(n):

if strlist[i].isdigit():

st.append(int(strlist[i]))

elif strlist[i]=='+':

a=st.pop()

b=st.pop()

st.append(a+b)

elif strlist[i]=='-':

a=st.pop()

b=st.pop()

st.append(a-b)

elif strlist[i]=='*':
PYTHON LAB MANUAL

a=st.pop()

b=st.pop()

st.append(a*b)

elif strlist[i]=='/':

a=st.pop()

b=st.pop()

st.append(a/b)

return st.pop()

str=input('enter any postfix expression:')

val=postevaluation(str)

print('ans=',val).

Output:
enter any postfix expression:4 5 *

ans= 20.

7.Write a program to multiply two matrices.


m,n=input('enter order of a matrix a:').split()

m=int(m)

n=int(n)

p,q=input('enter order of a matrix b:').split()

p=int(p)

q=int(q)

a=[[0 for i in range(m)] for j in range(n)]

b=[[0 for i in range(p)] for j in range(q)]

c=[[0 for i in range(m)] for j in range(q)]

if n!=p:

print('matrix can not multiplied:')


PYTHON LAB MANUAL

else:

print('enter {0} elements for matrix a:'.format(m*n))

for i in range(m):

for j in range(n):

a[i][j]=int(input())

print('enter {0} elements for matrix b:'.format(p*q))

for i in range(p):

for j in range(q):

b[i][j]=int(input())

for i in range(m):

for j in range(q):

for k in range(n):

c[i][j]+=a[i][k]*b[k][j]

print('matrix a is:')

for i in range(len(a)):

print(a[i])

print('matrix b is:')

for i in range(len(b)):

print(b[i])

print('matrix c is:')

for i in range(len(c)):

print(c[i]).

Output:
enter order of a matrix a:3 3

enter order of a matrix b:3 3

enter 9 elements for matrix a:


PYTHON LAB MANUAL

enter 9 elements for matrix b:

matrix a is:

[2, 3, 4]

[5, 6, 2]

[2, 1, 6]

matrix b is:

[7, 8, 9]

[2, 1, 4]
PYTHON LAB MANUAL

[1, 2, 4]

matrix c is:

[24, 27, 46]

[49, 50, 77]

[22, 29, 46].

8.write a program to find the roots of a quadratic equation.


import math

a=int(input('enter the value of a:'))

b=int(input('enter the value of b:'))

c=int(input('enter the value of c:'))

if a==0:

print('the equation is a single degree equation and having one real:')

r=-c/b

print('root is:'.r)

else:

d=b*b-4*a*c

if d==0:

print('the roots are real and equal:')

print('and equal root are',-b/(2*a))

elif d>0:

print('roots are real and different:')

r1=(-b+math.sqrt(d))/(2*a)

r2=(-b+math.sqrt(d))/(2*a)

print('root=',r1,'root2=',r2)

else:

print('roots are imaginary:')


PYTHON LAB MANUAL

rp=-b/(2*a)

ip=math.sqrt(abs(d))/(2*a)

print('root1',rp,'+i',ip)

print('root2',rp,'-i',ip).

Output:
enter the value of a:1

enter the value of b:-4

enter the value of c:4

the roots are real and equal:

and equal root are 2.0

9.write a program to insert a number in a sorted array.


def insertelement(a,el):

b=[]

n1=len(a)

for i in range(0,n1):

if a[i]<el:

b.append(a[i])

else:

break

b.append(el)

if i!=n-1:

b.append(a[i])

n2=i+1

for i in range(n2,n1):

b.append(a[i])

return b
PYTHON LAB MANUAL

n=int(input('enter size of array:'))

print('enter',n,'element')

a=[]

for i in range(n):

a.append(int(input()))

a.sort()

el=int(input('enter the element to insert:'))

print('array before insert:',a)

print('array after insert:',insertelement(a,el)).

Output:
enter size of array:5

enter 5 element

enter the element to insert:4

array before insert: [1, 2, 3, 6, 9]

array after insert: [1, 2, 3, 4, 6, 9].

10.write a program to check whether the given string is palindrome or not.


def sreverse(s):

return(s[::-1])

def ispalindrome(s):

rev=sreverse(s)

if s==rev:
PYTHON LAB MANUAL

return True

else:

return False

s=input('enter any string:')

ans=ispalindrome(s)

if ans:

print(s,'is a palindrome')

else:

print(s,'is not a palindrome').

Output:
enter any string:madam

madam is a palindrome.

11.write a python program letters,vowels and percentage of vowels in the


word using dictionary.
d={'vowels':0,'letters':0,'percentage':0}

word=input('enter any word:')

for x in word:

d['letters']+=1

if x=='a' or x=='e' or x=='i' or x=='o' or x=='u' or x=='A' or x=='E' or x=='I' or x=='O' or x=='U':

d['vowels']+=1

d['percentage']=(d['vowels']/d['letters'])*100

print('no of letters=',d['letters'])

print('no of vowels=',d['vowels'])

print('percentage of vowels=',d['percentage']).

Output:
enter any word:navya
PYTHON LAB MANUAL

no of letters= 5

no of vowels= 2

percentage of vowels= 40.0.

12.write a python program to check a given statement is a pangram or not


using function/module.
def ispangram(pharse):

c=0

alphabet='abcdefghijklmnopqrstuvwxyz'

pharseletter=''

for ch in pharse:

for letter in alphabet:

if ch==letter and ch not in pharseletter:

pharseletter+=ch

for ch in pharseletter:

for letter in alphabet:

if ch==letter:

c+=1

if c==26:

return True

else:

return False

pharse=input('enter any pharse:')

if ispangram(pharse):

print('the given sentence is pangram')

else:

print('the given sentence is not pangram').


PYTHON LAB MANUAL

Output:
enter any pharse:the quick brown fox jumps over the lazy dog

the given sentence is pangram.

13.write a python program for file operation.


while True:

print('1.open file in read mode')

print('2.open file in write mode')

print('3.current position of the file pointer')

print('4.reposition of the pointer at the begining')

print('5.exit')

choice=int(input('enter your choice[1-5]:'))

if choice==1:

fp=open('foo.txt','r')

print('name of the file is',fp.name)

print('file closed or not',fp.closed)

print('opening mode',fp.mode)

print('content of the file are\n',fp.read())

fp.close()

elif choice==2:

fp=open('foo.txt','w')

str=input('enter the strig:')

fp.write(str)

fp.close()

elif choice==3:

fp=open('foo.txt','r')

print('file pointer position before read()',fp.tell())


PYTHON LAB MANUAL

print('the contents of the file is',fp.read(8))

print('the pointer position after read()',fp.tell())

fp.close()

elif choice==4:

fp=open('foo.txt','a')

print('file pointer position after open ',fp.tell())

pos=fp.seek(0,0)

print('new file pointer position after seek(0,0)',fp.tell())

str=input('enter some more contents for the file:/')

fp.write(str)

print('now,file pointer position after write()',fp.tell())

fp.close()

else:

break

print('program ends here').

Output:
1.open file in read mode

2.open file in write mode

3.current position of the file pointer

4.reposition of the pointer at the begining

5.exit

enter your choice[1-5]:2

enter the strig:ubdt college

1.open file in read mode

2.open file in write mode

3.current position of the file pointer


PYTHON LAB MANUAL

4.reposition of the pointer at the begining

5.exit

enter your choice[1-5]:1

name of the file is foo.txt

file closed or not False

opening mode r

content of the file are

ubdt college

1.open file in read mode

2.open file in write mode

3.current position of the file pointer

4.reposition of the pointer at the begining

5.exit

enter your choice[1-5]:3

file pointer position before read() 0

the contents of the file is ubdt col

the pointer position after read() 8

1.open file in read mode

2.open file in write mode

3.current position of the file pointer

4.reposition of the pointer at the begining

5.exit

enter your choice[1-5]:4

file pointer position after open 12

new file pointer position after seek(0,0) 0

enter some more contents for the file:/mca enginearing


PYTHON LAB MANUAL

now,file pointer position after write() 27

1.open file in read mode

2.open file in write mode

3.current position of the file pointer

4.reposition of the pointer at the begining

5.exit

enter your choice[1-5]:5

program ends here.

14.write an object oriented python program to create two time objects.


class time:

def readtime(self):

self.hour=int(input('enter hour:'))

self.minute=int(input('enter minute:'))

self.second=int(input('enter second:'))

def addtime(self,other):

finishtime=time()

finishtime.hour=self.hour+other.hour

finishtime.minute=self.minute+other.minute

finishtime.second=self.second+other.second

if finishtime.second>=60:

finishtime.second-=60

finishtime.minute+=1

if finishtime.minute>=60:

finishtime.minute-=60

finishtime.hour+=1

return finishtime
PYTHON LAB MANUAL

def __str__(self):

return '{0:2d}:{1:2d}:{2:2d}'.format(self.hour,self.minute,self.second)

currenttime=time()

breadtime=time()

print('enter current time:')

currenttime.readtime()

print('enter breadmaking time:')

breadtime.readtime()

finishtime=time()

finishtime=currenttime.addtime(breadtime)

print('currenttime time:',currenttime)

print('bread making time:',breadtime)

print('bread finish time:',finishtime).

Output:
enter current time:

enter hour:2

enter minute:13

enter second:40

enter breadmaking time:

enter hour:3

enter minute:12

enter second:16

currenttime time: 2:13:40

bread making time: 3:12:16

bread finish time: 5:25:56

You might also like