Python Lab Manual PDF
Python Lab Manual PDF
I SEMESTER
2018 REGULATION
Prepared by
Dr. N. Saravanan,
Associate Professor / IT, KSRCE
1
LIST OF PROGRAMS
7. Merge sort
9. Multiply matrices
11. Find the most frequent words in a text read from a file
2
INDEX
Ex.
Date Topic Marks Signature
No
1 Compute the GCD of two numbers.
7 Merge sort
9 Multiply matrices
14
15
3
Ex. No: 1
AIM:
ALGORITHM :
Step 1: Start
Step 2: read two numbers to find the GCD
n1,n2. Step 3: rem=d1%d2
Step 4: while rem!=0
d1=d2
d2=rem Rem=d1%d2
Step 5: print GCD is
d2. Step 6: Stop
PROGRAM/SOURCE CODE :
d1=int(input("Enter a number:"))
d2=int(input("Enter another number"))
rem=d1%d2
while rem!=0:
d1=d2
d2=rem
rem=d1%d2
print("GCD of given number is",d2)
4
SAMPLE INPUT & OUTPUT :
Enter a number : 54
Enter another number : 24
GCD of given number is: 6
RESULT:
Thus the program to find the GCD of two numbers is executed and the output is obtained.
5
Ex. No: 2
AIM:
To write a python program to find the square root of a number (Newton’s method)
ALGORITHM :
Step 1: Define a function for Newton square root with two arguments.
Step 2: Assign the approximate value = 0.5*n.
Step 3: In each iteration, decide the range.
Step 4: Then calculate the approximate value.
Step 5: Return the approximate value.
Step 6: Finally print the values.
PROGRAM/SOURCE CODE :
6
RESULT:
Thus the program to find the square root (Newton’s method) is executed and the output is
obtained.
7
Ex. No: 3
ALGORITHM :
Step 1: Start.
Step 2: read base value
Step 3: Read exponent value.
Step 4: if base value is equal to one return base
Step 5: if base value is not equal to one return .
return(base*power(base,exp-1))
Step 6: print the result of program.
Step 7: Stop.
PROGRAM/SOURCE CODE:
def power(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
Enter base: 5
Enter exponential value: 3
Result: 125
8
RESULT:
Thus the program to find the exponentiation of a number is executed and the output is
obtained.
9
Ex. No: 4
ALGORITHM :
Step 1: Start.
Step 2: Read the number of element in the list.
Step 3: Read the number until loop n-1.
Step 4: Then Append the all element in list
Step 5: Goto STEP-3 upto n-1.
Step 6: Sort the listed values.
Step 7: Print the a[n-1] value.
PROGRAM/SOURCE CODE :
a=[]
n=int(input("Enter number of elements:"))
for i in range(1,n+1):
b=int(input("Enter element:"))
a.append(b)
a.sort()
print("Largest element is:",a[n-1])
10
RESULT:
Thus the program to find the Maximum of a List of numbers is executed and the output is
obtained.
11
Ex. No: 5a
LINEAR SEARCH
AIM:
ALGORITHM :
Step 1: Start
Step 2: Read the element in list.
Step 3: Read the searching element from the user
Step 4: Assign to FALSE flag value
Step 5: Search the element with using for loop until length of list
Step 6: if value is found assign the flag value is true
Step7: Then print the output of founded value and position.
Step8: if value is not found then go to next step
Step9: print the not found statement
PROGRAM/SOURCE CODE :
a=[]
n=int(input("Enter the number of elements:"))
for i in range(1,n+1):
b=int(input("Enter Element:"))
a.append(b)
x = int(input("Enter number to search: "))
found = False
for i in range(len(a)):
if(a[i] == x):
found = True
print("%d found at %dth position"%(x,i+1))
break
if(found == False):
print("%d is not in list"%x)
12
SAMPLE INPUT & OUTPUT :
RESULT:
Thus the program to perform linear Search is executed and the output is obtained.
13
Ex. No: 5b
BINARY SEARCH
AIM:
To write a python program to perform the binary search.
ALGORITHM :
Given a list L of n elements with values or records L0, L1, …, Ln-1, sorted in ascending order,
and given key/target value K, binary search is used to find the index of K in L
1. Set a variable start to 0 and another variable end to n-1(size of the list)
2. if start > end break the algorithm, as it works only on sorted lists
3. calculate mid as (start + end)/2
4. if the key element is
• equal to mid, the search is done return position of mid
• greater than mid, set start to mid + 1 and repeat from step 2
• less than mid, set end to mid — 1 and repeat from step 2
PROGRAM/SOURCE CODE :
14
lst = []
size = int(input("Enter size of list: \t"))
for n in range(size):
numbers = int(input("Enter any number: \t"))
lst.append(numbers)
lst.sort()
print('\n\nThe list will be sorted, the sorted list is:', lst)
RESULT:
Thus the program to perform Binary Search is executed and the output is obtained.
15
Ex. No: 6a
SELECTION SORT
AIM:
To write a python program to perform selection sort.
ALGORITHM:
Step 1: Read the number of elements for the list from the user.
Step 2: Using for loop insert the elements in the list.
Step 3: Initialize the minimum element as min=numbers[i].
Step 4: Using the swap method the elements are sorted accordingly.
Step 5: Print the sorted list.
PROGRAM/SOURCE CODE:
def selectionSort(nlist,size):
for fillslot in range(size-1,0,-1):
maxpos=0
for location in range(1,fillslot+1):
if nlist[location]>nlist[maxpos]:
maxpos = location
nlist[fillslot],nlist[maxpos]= nlist[maxpos],nlist[fillslot]
nlist = []
size = int(input("Enter size of list: \t"))
for n in range(size):
numbers = int(input("Enter any number: \t"))
nlist.append(numbers)
16
SAMPLE INPUT & OUTPUT:
RESULT:
Thus the program to perform Selection Sort is executed and the output is obtained.
17
Ex. No: 6b
INSERTION SORT
AIM:
To write a python program to perform insertion sort.
ALGORITHM:
Step 1: Read the number of elements for the list from the user.
Step 2: Define the function for insertion Sort
Step 3: Then initialize the loop as follows.
For i in range (1, len(alist)
Step 4: Using While loop check the condition
Position > 0 and alist[position-1]>currentvalue
Step 5: If the condition is true swap the values by changing the position.
Step 6: Print the sorted list.
PROGRAM/SOURCE CODE:
def insertionSort(alist):
for index in range(1,len(alist)):
currentvalue = alist[index]
position = index
while position>0 and alist[position-1]>currentvalue:
alist[position]=alist[position-1]
position = position-1
alist[position]=currentvalue
alist = []
size = int(input("Enter size of list: \t"))
for n in range(size):
numbers = int(input("Enter any number: \t"))
alist.append(numbers)
18
SAMPLE INPUT & OUTPUT:
RESULT:
Thus the program to perform Insertion Sort is executed and the output is obtained.
19
Ex. No: 7
MERGE SORT
AIM:
To write a python program to perform Merge sort.
ALGORITHM:
Step 1: Compute the function def mergeSort(alist)
Step 2: With in the if condition
if len(alist)>1:
mid = len(alist)//2
lefthalf=alist[:mid]
righthalf=alist[mid;]
Step 3: Then merge the left half and right half .
Step 4: Then initialize the condition for merge(right half)
Step 5: print the OUTPUT : in step by step execution
PROGRAM/SOURCE CODE:
def MergeSort(alist):
print("Splitting ",alist)
if len(alist)>1:
mid = len(alist)//2
lefthalf = alist[:mid]
righthalf = alist[mid:]
MergeSort(lefthalf)
MergeSort(righthalf)
i=0
j=0
k=0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i] < righthalf[j]:
alist[k]=lefthalf[i]
i=i+1
20
else:
alist[k]=righthalf[j]
j=j+1
k=k+1
MergeSort(alist)
print(alist)
21
Splitting [26, 93]
Splitting [26]
Merging [26]
Splitting [93]
Merging [93]
Merging [26, 93]
Merging [26, 54, 93]
Splitting [17, 77, 31]
Splitting [17]
Merging [17]
Splitting [77, 31]
Splitting [77]
Merging [77]
Splitting [31]
Merging [31]
Merging [31, 77]
Merging [17, 31, 77]
Merging [17, 26, 31, 54, 77, 93]
[17, 26, 31, 54, 77, 93]
RESULT:
Thus the program to perform Merge Sort is executed and the output is obtained.
22
Ex. No: 8
FIRST N PRIME NUMBERS
AIM:
To write a python program to find first n prime numbers.
ALGORITHM:
Step1: Take in the upper limit for the range and store it in a variable.
Step 2: Let the first for loop range from 2 to the upper limit.
Step3: Initialize the count variable to 0.
Step4: Let the second for loop range from 2 to half of the number (excluding 1 and the
number itself).
Step 5: Then find the number of divisors using the if statement and increment the count
variable each time.
Step 6: If the number of divisors is lesser than or equal to 0, the number is prime.
Step 7: Print the final result.
PROGRAM/SOURCE CODE:
i=1
x = int(input("Enter the number:"))
for k in range (1, (x+1), 1):
c=0;
for j in range (1, (i+1), 1):
a = i%j
if (a==0):
c = c+1
if (c==2):
print (i)
else:
k = k-1
i=i+1
23
SAMPLE INPUT & OUTPUT:
RESULT:
Thus the program to find first n prime numbers is executed and the output is obtained.
24
Ex. No: 9
MULTIPLICATION OF TWO MATRICES
AIM:
To write a python program to perform matrix multiplication.
ALGORITHM :
Step 1: Assume the values for the first matrix as X
Step 2: Assume the values for the first matrix as Y
Step 3: Assume the resultant matrix = [[0,0,0],[0,0,0], [0,0,0]]
Step 4: Then iterate through rows of X
Step 5: Then iterate through rows of Y
Step 6: Multiply and then Print the output
PROGRAM/SOURCE CODE :
# 3x3 matrix
X = [ [12,7,3], [4 ,5,6], [7 ,8,9]]
# 3x4 matrix
Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]]
# result is 3x4
result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]]
# iterate through rows of X
for i in range(len(X)):
# iterate through columns of Y
for j in range(len(Y[0])):
# iterate through rows of Y
for k in range(len(Y)):
result[i][j] += X[i][k] * Y[k][j]
for r in result:
print(r)
25
RESULT:
Thus the program to perform matrix Multiplication is executed and the output is obtained.
26
Ex. No: 10
PROGRAMS THAT TAKE COMMAND LINE ARGUMENTS
(WORD COUNT)
AIM:
To write a python program to perform command line arguments (word count).
ALGORITHM :
Step 1: Start
Step 2: Find the length of CLA.
Step 3: Store the argument list to a variable namely cmdargs.
Step 4: Print the total number of arguments passed to the script.
Step 5: Print the argument list separately.
Step 6: Stop
PROGRAM/SOURCE CODE :
import sys
total = len(sys.argv)
cmdargs = str(sys.argv)
print ("The total numbers of args passed to the script: %d " % total)
print ("Args list: %s " % cmdargs)
print ("Script name: %s" % str(sys.argv[0]))
print ("First argument: %s" % str(sys.argv[0]))
print ("Second argument: %s" % str(sys.argv[1]))
print ("Third argument: %s" % str(sys.argv[2]))
27
SAMPLE INPUT & OUTPUT:
RESULT:
Thus the program to count the words is executed and the output is obtained.
28
Ex. No: 11
AIM:
To write a python program to find the most frequent words from a file.
ALGORITHM :
Step 1: User must enter a file name and the letter to be searched.
Step 2: The file is opened using the open() function in the read mode.
Step 3: A for loop is used to read through each line in the file
Step 4: Each line is split into a list of words using split().
Step 5: A for loop is used to traverse through the words list and another for loop is used to
traverse through the letters in the word.
Step 6: If the letter provided by the user and the letter encountered over iteration are equal, the
letter count is incremented.
Step 7: The final count of occurrences of the letter is printed
PROGRAM/SOURCE CODE :
k=0
for line in f:
words = line.split()
for i in words:
for letter in i:
if(letter==l):
29
k=k+1
print(k)
Output:
Enter file name: out.txt
Enter letter to be searched:o
Occurrences of the letter:
5
RESULT:
Thus the program to find the most frequent words in a text is executed and the output is
obtained.
30
Ex. No: 12
AIM:
To write a python program to simulate elliptical orbits in pygame.
ALGORITHM :
Step 1: Import the necessary header files for the implementation of this pygame.
Step 2: Set the display mode for the screen using
screen=pygame.display.set_mode((600,300))
Step 3: Step 4: Set the radius for sun, moon and their orbit.
Step 5: Set the time for the pygame orbit clock=pygame.time.Clock()
Step 6: Update the earth position.
Step 7: Again update moon position based on earth position.
Step 8: Update the moon and earth angles.
Step 9: Reset the screen and draw the stars, sun, moon and the earth.
Step 10: Set the clock tick as (5) and exit.
PROGRAM/SOURCE CODE :
import pygame
import math
import sys
pygame.init()
clock = pygame.time.Clock()
31
while(True):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
xRadius = 250
yRadius = 100
for degree in range(0,360,10):
x1 = int(math.cos(degree * 2 * math.pi / 360) * xRadius) + 300
y1 = int(math.sin(degree * 2 * math.pi / 360) * yRadius) + 150
screen.fill((0, 0, 0))
pygame.draw.circle(screen, (255, 0, 0), [300, 150], 35)
pygame.draw.ellipse(screen, (255, 255, 255), [50, 50, 500, 200], 1)
pygame.draw.circle(screen, (0, 0, 255), [x1, y1], 15)
pygame.display.flip()
clock.tick(5)
32
RESULT:
Thus the simulation of elliptical curve orbit using pygame is executed and the output is obtained.
33
Ex. No: 13
SIMULATE BOUNCING BALL USING PYGAME
AIM:
To write a python program to simulate bouncing ball using pygame.
ALGORITHM:
Step 1: Import the necessary files for the implementation of this Pygame.
Step 2: Set the display mode for the screen as 700 300
Step 3: Now set the display mode for the pygame to bounce
pygame.display.set_caption(“Bounce ball”)
Step 4: Develop the balls image from the path .
ball = pygame.image.load("ball.jpg")
ballrect = ball.get_rect()
Step 5: Set the initial direction to move the ball.
Step 6: Set the condition for quit.
Step 7: Exit from the pygame.
PROGRAM/SOURCE CODE :
import sys, pygame
pygame.init()
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.jpg")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
34
if event.type == pygame.QUIT:
sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
35
RESULT:
Thus the program to simulate bouncing ball using pygame is executed and the output is
obtained.
36
VIVA QUESTIONS
1. What is Python?
37
9. How will you create a dictionary in python?
12. Mention what are the rules for local and global variables in Python?
13. How will you convert a single character to its integer value in python?
38
17. How will you capitalizes first letter of string?
25. How to copy the data from one file to another file?
39