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

python lab manual 1 - 15 (1)

Uploaded by

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

python lab manual 1 - 15 (1)

Uploaded by

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

Ex No:1(i): Greatest Common Divisor of Two Numbers

Aim:
To calculate the Greatest Common Divisor of two numbers using mathematical functions.

Logic:

 For example, get two numbers 8 and 16 during runtime,

 The divisor for the number 8 is 1,2,4,8

 The divisor for the number 16 is 1,2,4,8,16

 The common divisor for the number 8 and 16 is 1,2,4,8

 The Greatest common Divisor of two numbers is 8

Procedure:

 Select start menu click all programs  click python 3.7.3

 Click IDLEclick filenew file edit the script

 Save it as .py file

 Press f5 or run  run module to run the program.

Program:

import math

a=int(input(‘Enter the first number:’)) #16

b=int(input(‘Enter the second number:’)) # 8

c= math.gcd(a,b) #1,2,4,8

print(“The GCD of two numbers is:”,c) #8

Output:

Enter the first number:16


Enter the second number:8
The GCD of two numbers is: 8

Result:
Thus, the program to find the GCD of two numbers is executed successfully.
ExNo:1(ii) Prime Numbers
Aim:

To check the given number is prime number or not in the given range.

Logic:
 The number which is divisible by 1 and itself is called prime numbers.
 For example, 3 is divisible by 1 and 3 itself.
 9 is divisible by 1,3,9. It is not a prime number.

Procedure:

 Select start menu click all programs  click python 3.7.3

 Click IDLEclick filenew file edit the script

 Save it as .py file


 Press f5 or run  run module to run the program

Program:
n1 = int(input('enter the start range:'))# 1

n2 = int(input('enter the end range:')) #10

for x in range(n1,n2+1):
if x>=2:
for y in range(2,x):
if (x%y==0):
break
else:
print(x)

Output:
enter the start range:1
enter the end range:10
2
3
5
7

Result:
Thus, the program to find the prime numbers of a given range is executed successfully.
Exno.2(i) Leap Year

Aim:

To write a python program to check the given year is leap year or not.

Logic:

 To check a year is a leap year, divide the year by 4. If it is fully divisible by 4 it is a leap year.
 For example, the year 2016 is divisible by 4 so it is a leap year whereas the year 2015 is not so
it is not a leap year.
 However century years like 300,400,1600,2000 need to be divided by 400 to check whether
they are leap year or not.
 We should also check a condition if the given year is should not be zero if divided by 100.

Procedure:

 Select start menu click all programs  click python 3.7.3

 Click IDLEclick file new file edit the script

 Save it as .py file

 Press f5 or run  run module to run the program

Program:

year = int(input('Enter the year:')) #1002,2004

if ((year%4==0 and year%100!=0) or year%400==0):

print("The given year", year," is a leap year")

else:

print("The given year", year," is not a leap year")

Output:

Enter the year:1002

The given year 1002 is not a leap year

Enter the year:2004

The given year 2004 is a leap year

Result:
Thus, the program to find the given year is a leap year or not a leap year is executed successfully.
Exno:2(ii) Armstrong Numbers

Aim:

To write a python program to print Armstrong numbers between a given a range.

Logic:

 A number is thought of as an Armstrong number if the sum of its own digits raised to the
power number of digits gives the number itself.
 For example, 153 is 3 digits in this so the given number is evaluated like 13 +53+33
=1+125+27153 after evaluated the value which is same is called Armstrong number.
 33 here 2 digits only so 32 +32 18 which is not an Armstrong number.

Procedure:

 Select start menu click all programs  click python 3.7.3

 Click IDLEclick file new file edit the script

 Save it as .py file

 Press f5 or run  run module to run the program.

Program:

n1= int(input("Enter the starting value:")) #100

n2= int(input("Enter the stopping value:")) #1000

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

number=i

sum=0

no_of_digits=len(str(i))

while (i!=0):

digit=i%10

sum=sum+digit**no_of_digits

i=i//10

if sum==number:

print(number)
Output:

Enter the start value:100

Enter the stop value:1000

153

370

371

407

Result:
Thus, the program to find a given number is an Armstrong number or not is executed successfully.
Exno:3(i) Basic String Operations

Aim:

To write a python program to do basic trim and slice operations on String.

Logic:

 Slicing- Slicing is a process of taking a range of characters from the given string.

 For slicing follow the syntax “ variablename[start:stop] ”


 Stripping- Strip(chars) is used to remove the characters given in the “chars” from
the beginning and end of the string

 For stripping follow the syntax “ variablename.strip(chars) ”

Procedure:

 Select start menu click all programs  click python 3.7.3

 Click IDLEclick filenew file edit the script

 Save it as .py file

 Press f5 or run  run module to run the program.

Program:

s='Hello World'

print('The sliced string from index 0 to 7 is:',s[:8]) # Hello Wo

print('The sliced string from index 2 to 9 is:',s[2:10])#llo Worl

print('The sliced string from index 4 to last is:',s[4:]) # o World

s1='Hello World'
print('The string after removing leading and trailing Hash symbol is:',s1.strip('Hd'))

print('The string after removing leading Hash symbol is:',s1.lstrip('H')) # ello World

print('The string after removing trailing Hash symbol is:',s1.rstrip('d')) # Hello Worl
Output:

The sliced string from index 0 to 7 is: Hello Wo

The sliced string from index 2 to 9 is: llo Worl

The sliced string from index 4 to last is: o World

The string after removing leading and trailing Hash symbol is: ello Worl

The string after removing leading Hash symbol is: ello World

The string after removing trailing Hash symbol is: Hello Worl

Result:

Thus, the program to perform the basic operations of a given string is executed successfully.
Exno:3(ii) Calculate the number of Vowels, Characters and Whitespaces

Aim:

To write a python program to accept line of text and find the number of characters, vowels
and blank spaces on it.

Logic:

Use for loop and nested if conditions to count number of vowels, characters and blank
spaces for a given string.

Procedure:

 Select start menu click all programs  click python 3.7.3

 Click IDLEclick filenew file edit the script

 Save it as .py file

 Press f5 or run  run module to run the program.

Program:

s = input("Enter a String:") # python is user friendly


vowels = 0
characters = 0
spaces = 0
s = s.lower()
vow = 'aeiou'
for i in s:
if i in vow:
vowels = vowels+1
if (i>='a ' and i<='z'):
characters = characters+1
else:
spaces = spaces+1
print("Number of vowels:", vowels )
print("Number of characters:", characters )
print("Number of whitespaces:", spaces )
Output:

Enter a String: python is user friendly

Number of vowels: 6

Number of characters: 20

Number of whitespaces: 3

Result:

Thus, the program to calculate the number of vowels, characters and whitespaces of a given string is
executed successfully.
Exno:4(i) To display numbers which are divided by 3 but not multiple of 5

Aim:

Write a Python Program using function to display all such numbers which is divided by 3 but not
multiple of 5 in a given range.
Logic:

 The given number should be divisible by 3 but it should not be a multiple of 5.

Example:

 12 is divisible by 3 but not by 5 (True condition).


 15 is divisible by both 3 and 5 (False condition).

Procedure:

 Select start menu click all programs  click python 3.7.3

 Click IDLEclick filenew file edit the script

 Save it as .py file

 Press f5 or run  run module to run the program.

Program:

n1=int(input('Enter Starting Value:')) #100

n2=int(input('Enter Stopping Value:')) #200

print('The numbers which are divisible by 3 but not a multiple of 5 are: ')

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

if i%5!=0 and i%3==0:

print(i, '\t', end='')

Output:
Enter Starting Value:100
Enter Stopping Value:200
The numbers which are divisible by 3 but not a multiple of 5 are:

102 108 111 114 117 123 126 129 132 138 141 144 147
153 156 159 162 168 171 174 177 183 186 189 192 198
Result:
Thus, the program to display numbers which are divided by 3 but not multiple of 5 in a given range is
executed successfully.
Exno:4(ii) Fibonacci Series

Aim:

To write a python program using recursion to print ’n’ terms in Fibonacci series.

Logic:

 A sequence of type 0,1,1,2,3,5,8,……. is called Fibonacci series.

 In general the succeeding number is got by adding the two preceding number.

 For example 0 and 1 are base values:

0+1=1  0,1,1 then 1+1=2  0,1,1,2 followed by 1+2=3  0,1,1,2,3,… and so on.

 The recursive formula fn = fn-1+fn-2, n>1.

Procedure:

 Select start menu click all programs  click python 3.7.3

 Click IDLEclick filenew file edit the script

 Save it as .py file

 Press f5 or run  run module to run the program.

Program:

#Recursive Function

def fib(n):

if n==1:

return 0

elif n==2:

return 1

else:

return(fib(n-1)+fib(n-2))

# Main Program

n = int(input('Enter the value of n:')) #10

print("The fibonacci sequence for the given number",n,"is:")

for i in range(1,n+1):

print(fib(i), end=' ') # Function calling


Output:

Enter the value of n:10

The Fibonacci sequence for the given number 10 is:

0 1 1 2 3 5 8 13 21 34

Result:

Thus, the program to calculate the Fibonacci sequence for the given number is executed
successfully
EX.NO:05 Adding String

AIM:
To write python program to add ‘ing’ at the end of a given
string if the string has 3 or more characters. If the given string is already ends
with ‘ing’ then add ‘ly’ instead. If the string has less than 3 characters, leave it
unchanged.
LOGIC:
To satisfy the above condition classify them, using Nested ifstatement.
PROCEDURE:
 Select start menu →click all programs → click python 3.7.3
 Click IDLE → click file → new file → edit the script
 Save it as .py file
 Press f5 or run → run module to run the program.
PROGRAM:
s=input('Enter the string:') #good morning
s1=s
l=len(s) #12
if l>=3: #True
if s[-3:]=='ing':#True
s=s+'ly'#goodmorning+ly
else:
s=s+'ing'
print('The given string is :',s1)#good morning
print('The modified string is:',s)#good morningly
O/P:
Enter the string:good morning The given
string is : good morning
The modified string is: good morningly Enter
the string:what
The given string is : what
The modified string is: whating Enter
the string:go
The given string is : go
The modified string is: go

Result:
Thus the python program of adding ‘ing’ and ‘ly’ was executed successfully
EX.NO:06 Minimum And Maximum Of List

AIM:

To program a python program to find minimum and maximum of alist of number

LOGIC:

 Using min and max method to find minimum and maximumin created list
 And using index method to find the position of the minimum and
maximum in created list

PROCEDURE:

 Select start menu →click all programs → click python 3.7.3


 Click IDLE→ click file→ new file →edit the script
 Save it as .py file
 Press f5 or run → run module to run the program.

PROGRAM:
l=[]
n=int(input('Enter the total number:'))#4
print('Enter the number one by one')
for i in range(n): #0 1 2 3
x=int(input())
l.append(x) #l=[87,90,32,5]
min1=min(l) #5
max1=max(l)#90
posmin=l.index(min1)#3
posmax=l.index(max1) #1
print('the minimun number among the given numbers is:',min1)#5
print('the position of the minimun number is:',posmin)#3
print('the maximum number among the given number is:',max1)#90
print('the position of the maximum number is:',posmax)#1

O/P:

Enter the total number:4


Enter the number one by one
87
90
32
5
the minimun number among the given numbers is: 5
the position of the minimun number is: 3
the maximum number among the given number is: 90
the position of the maximum number is: 1

Result:

Thus the python program of finding minimum and maximum value of the list is executed successfully
EX.NO:07 Display A List In Reverse Order

AIM:

To write a program to display a list in reverse order

LOGIC:

 Using reverse method, we can display a list in reverse order and using for
statement

PROCEDURE:

 Select start menu →click all programs → click python 3.7.3


 Click IDLE → click file → new file → edit the script
 Save it as .py file
 Press f5 or run → run module to run the program.

PROGRAM:

l=[] #empty list


n=int(input('Enter the total number of list elements:'))#5
print('Enterthe elements one by one:')
for i in range(n): #for loop execute 5 times since n value is 5. i value assigned from 0 to
4
x = int(input()) #x [89,2,78,90,67]
l.append(x) #x value is add to l
print('The original list is:',l) #now l=[89,2,78,90,67]
print('Thereversed list is:',end='')
l.reverse()
print(l)#l=[67,90,78,2,89]
O/P:

Enter the total number of list elements:5


Enterthe elements one by one:
89
2
78
90
67
The original list is: [89, 2, 78, 90, 67]
The reversed list is:[67, 90, 78, 2, 89]

Result:
Thus the python program to display a list in reverse order is executed
successfully
EX.NO: (8)
Display The First Half Tuple And SecondHalf Tuple

AIM:

To write python program to take a list of words and return the length of the longest
one using string

LOGIC:
 Using len method and floor division // to find the first half values of tuple
and second half values of tuple.

PROCEDURE:
 Select start menu →click all programs → click python 3.7.3
 Click IDLE→ click file→ new file →edit the script
 Save it as .py file
 Press f5 or run → run module to run the program.
PROGRAM:
t=(3,4,5,6,7,19,70,'good','bad',89,76)
l=len(t)#length of the tuple is 11
print('The given tuple is:',t)#(3,4,5,6,7,19,70,'good','bad',89,76)
print('First half tuple values are:',t[:l//2])#t[:11//2] is (3, 4, 5, 6, 7)
print('Second half tuple values are:',t[l//2:])#t[11//2:] is (19, 70, 'good', 'bad', 89, 76)

O/P:
The given tuple is: (3, 4, 5, 6, 7, 19, 70, 'good', 'bad', 89, 76)
First half tuple values are: (3, 4, 5, 6, 7)
Second half tuple values are: (19, 70, 'good', 'bad', 89, 76)

RESULT:
Thus, the program to print the first half values and second half values of tuple is
executed successfully.
PART-B
Ex No: 09 Find The Longest String In List
AIM:
To write a python program to take a list of words and return the length of the longest one
using String.

Logic:
 The longest String values entered in the list to be identified.
 For example,[‘Ant’,’Apple’,’Aeroplane’]
 Here Aeroplane was the longest string.

Procedure:
 Select start menu →click all programs → click python 3.7.3
 Click IDLE→ click file→ new file →edit the script
 Save it as .py file
 Press f5 or run → run module to run the program.

PROGRAM:

L=[]
N=int(input(‘Enter the number of words in the list:’’)) #5
print(‘Enter the words one by one’)# luck good beautiful welcome long
for i in range(N): #0 1 2 3 4
w=input()
L.append(w)
X=L[0]
L1=len(x)
for i in L:
L2=len(i)
If L2 >L1:
L1 = L2
X=i
print(‘the longest word in the list {} is {}’.format(1,x))
OUTPUT:
Enter the number of words in the list : 4
Enter the words one by one
ant
apple
aeroplane
axe
The longest word in the list ['ant', 'apple', 'aeroplane', 'axe'] is aeroplane

Result:
Thus, the python program to return the length of the longest one using string is
identified successfully.
Ex no -10 Linear Search
Aim:
To write a python program to find an element in a given set of elements using Linear
Search.
Logic:
 Let a be a list of n data and let x be the data to be searched.Our aim is to find
whether x is present in the list . if x is in the list, print Search Success . it not print
Search Failed.
 Compare x with a[0],if equals print search success,else compare x with a[1] if equals
print search success and so on . This process is repeated till the last list element s[n-1].
 If no list value matches print Search failed.
Procedure:
 Select start menu →click all programs → click python 3.7.3
 Click IDLE→ click file→ new file →edit the script
 Save it as .py file
 Press f5 or run → run module to run the program.
Program:
n=int(input('Enter the number of data to sort:')) #7
a=[]
for i in range(n):#0 1 2 3 4 5 6
x=int(input('Enter the next data:'))
a.append(x)
x=int(input('Enter the element to search'))# element to search in sort
for i in range(n):#0 1 2 3 4 5 6
if a[i]==x:
print("the element {} is present in position {}".format(x,i))
break
if i==n-1:
print('search failed')
Output:
Enter the number of data to
sort:7 Enter the next data:10
Enter the next data:7
Enter the next data:13
Enter the next data:9
Enter the next data:25
Enter the next data:17
Enter the next data:15
Enter the element to search 25
the element 25 is present in position 4

Result:
Thus, the python program to find an element in a given set of elements using linear
search was executed successfully.
Exno:11 Sorting
Aim:
To write a python program to sort a set of elements using selection sort.
Logic:
 Let a be a list of n numbers.our aim is to sort the numbers in the list in ascending order.
 The smallest element index position in the list a[0] ,a[1],….,a[n-1]say k1 and
interchange the values a[0] and a[k1]
 The next smallest element index position in the list a[1],a[2],….a[n-1] say k2
and interchange the values a[1] and a[k2].
 This process is repeated up to (n-1)th selection is made
Procedure:
 Select start menu →click all programs → click python 3.7.3
 Click IDLE→ click file→ new file →edit the script
 Save it as .py file
 Press f5 or run → run module to run the program.

Program:
n=int(input('Enter the number of data to sort:')) # 6
a=[]
for i in range(n):# i=0 1 2 3 4 5
x=int(input('Enter the next data:'))
a.append(x) # the given element is appended [ , , ]
print('The original list is:',a)
for i in range(n):# i=0 1 2 3 4 5
min=a[i]
t=i
for j in range(i+1,n):

if min>a[j]:
min=a[j]
t=j
a[t]=a[i]
a[i]=min
print('the sorted list is:',a)
Output:
Enter the number of data to
sort:4 Enter the next data:12
Enter the next data:34
Enter the next data:56
Enter the next data:67
The original list is: [12, 34, 56, 67]
the sorted list is: [12, 34, 56, 67]

Result:
Thus the python program to sort a set of elements using selection sort was executed
successfully.
Ex.no – 12 Multiply Two Matrics
Aim:
To write a python program to multiply two matrices.
Logic:
 Number of columns in the first matrix must equal to the number of rows of the
second matrix
 If A=m x p and B=n
x p C=A*B
=m x n * n x p
C=m x

A= * B= = C=

Procedure:
 Select start menu →click all programs → click python 3.7.3
 Click IDLE→ click file→ new file →edit the script
 Save it as .py file
 Press f5 or run → run module to run the program.
Program:
a=[[1,2,3],[4,5,6]]
b=[[1,2,3],[4,5,6],[1,3,3]]
c=[[0,0,0],[0,0,0]]
m=len(a) # 2
n=len(b) # 3
for i in range(m): # 0 1
for j in range(len(b)): # 0 1 2
for k in range(n): # 0 1 2
c[i][j]+=a[i][k]*b[k][j]
print('the product of the two given matrix is')
for i in range(m):
for j in range(len(b)):
print(c[i][j],end='')
print()
output:
The product of the two given matrix is
12 21 24
30 51 60

Result:
Thus the python program to multiply two matrices was executed successfully.
Ex no – 13 Operations on Tuple
Aim:
To write a python program to demonstrate different operations on tuple.
Logic:
 This program to implement the following operation on tuple
 Concatenation – joining two tuples(string1 + string2 = string 3)
 Repetition – how many times to repeat (sring * no of times)
 Length – finding the length of the tuple( len (list name))
Procedure:
 Select start menu →click all programs → click python 3.7.3
 Click IDLE→ click file→ new file →edit the script
 Save it as .py file
 Press f5 or run → run module to run the program.

Program:
t1=(17,'bat',97.5,'cat','dog')
t2=(89.7,45,76)
t3=t1+t2 # (17,'bat',97.5,'cat','dog') + (89.7,45,76)
t4=t2*2 # (17,'bat',97.5,'cat','dog') * 2
l=len(t3) # 8
print('the concatenation tuple is:',t3)
print('the repetition of tuple is:',t4)
print('the length of the tuple is:',l)

Output:
the concatenation tuple is: (17, 'bat', 97.5, 'cat', 'dog', 89.7, 45, 76)
the repetition of tuple is: (89.7, 45, 76, 89.7, 45, 76)
the length of the tuple is: 8

Result:
Thus the python program to demonstrate different operations on tuple was executed
successfully.
Ex no -14 Dictionary
Aim:
To write a python program to demonstrate to use dictionary and related functions.
Logic:
 This program to implement the following operations on dictionary
 Length – to find the length of the dictionary
 Copy – to copy the dictionary
 To remove an element from a specified key
 To get an element from the given key
 To view key-value pair as a tuple in list
 To get the values as a list
 To remove the last item
 To remove all elements’ ‘’
Procedure:
 Select start menu →click all programs → click python 3.7.3
 Click IDLE→ click file→ new file →edit the script
 Save it as .py file
 Press f5 or run → run module to run the program.
Program:
d={1001:'ramu',1002:'babu',1003:'kumar',1004:'somu',1005:'sita'}
print('the length of the dictionary is:',len(d))#5
print('the copied dictionary is:',d.copy())
print('the removed element is:',d.pop(1001)) #ramu
print('the dictionary d after removing 1002 is:',d)
print('the element in 1005 key is:',d.get(1005)) #sita
print('the key-value pair as a tuple in a list is:',d.items())
print('the dictionary values as a list is:',d.values())
print('the removed last item from dictionary is:',d.popitem())#(1005,’sita’)
d.clear()
print('the dictionary after removing all elements:',d)#{}
output:
the length of the dictionary is: 5
the copied dictionary is: {1001: 'ramu', 1002: 'babu', 1003: 'kumar', 1004: 'somu', 1005:
'sita'} the removed element is: ramu
the dictionary d after removing 1002 is: {1002: 'babu', 1003: 'kumar', 1004: 'somu', 1005:
'sita'} the element in 1005 key is: sita
the key-value pair as a tuple in a list is: dict_items([(1002, 'babu'), (1003, 'kumar'), (1004,
'somu'), (1005, 'sita')])
the dictionary values as a list is: dict_values(['babu', 'kumar', 'somu', 'sita'])
the removed last item from dictionary is: (1005, 'sita')
the dictionary after removing all elements: {}

Result:
Thus the python to use dictionary and related functions was executed successfully.
Ex no – 15 Copying Content From One File To Another File
Aim:
To write a python program to copy file content from one file to another and display
number of words copied.
Logic:
 To copy the content of one file to another file and to display number of words to be
copied
Procedure:
 Select start menu →click all programs → click python 3.7.3
 Click IDLE→ click file→ new file →edit the script
 Save it as .py file
 Press f5 or run → run module to run the program.
Program:
with open('file1.txt','w')as f: #creating file1
n=int(input('enter the number of lines of data:'))
for i in range(n):
data=input('enter the next line of data:')
f.write(data+'\n')
with open('file1.txt','r') as f: #opening file 1 in read mode
with open('file2.txt','w') as s: #opening file 1 in write mode
for i in f:
s.write(i)
with open('file2.txt','r') as s:
print('the content of file2 is:\n',s.read())
with open('file1.txt','r') as f:
d=f.read()
l=d.split()
count=0
for i in l:
count=count+1
print('number of words copied from file1 to file2 is:', count)
output:
enter the number of lines of data:3
enter the next line of data:welcome to the
enter the next line of data:world of python
enter the next line of data:good morning
the content of file2 is:
welcome to the
world of python
good morning
number of words copied from file1 to file2 is: 8

Result:
Thus the python program to copy file contents from one file to another and the number
of words copied are displayed.

You might also like