0% found this document useful (1 vote)
597 views39 pages

Python Lab Manual PDF

The document is a lab manual for the Python Programming Laboratory course at K. S. R. College of Engineering, Tiruchengode. It contains 13 programs to be completed as part of the course. The programs cover topics like computing GCD, square roots, exponentiation, maximum/minimum of lists, searching algorithms like linear and binary search, sorting algorithms like selection, insertion and merge sort, prime numbers, matrix multiplication, command line arguments, word counting, and simulations using Pygame. Each program is listed with its aim, algorithm, sample code, input/output and result.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (1 vote)
597 views39 pages

Python Lab Manual PDF

The document is a lab manual for the Python Programming Laboratory course at K. S. R. College of Engineering, Tiruchengode. It contains 13 programs to be completed as part of the course. The programs cover topics like computing GCD, square roots, exponentiation, maximum/minimum of lists, searching algorithms like linear and binary search, sorting algorithms like selection, insertion and merge sort, prime numbers, matrix multiplication, command line arguments, word counting, and simulations using Pygame. Each program is listed with its aim, algorithm, sample code, input/output and result.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 39

K. S. R.

COLLEGE OF ENGINEERING, TIRUCHENGODE – 637 215


(Autonomous)

DEPARTMENT OF INFORMATION TECHNOLOGY


LAB MANUAL

I SEMESTER

18IT221 - PYTHON PROGRAMMING LABORATORY

2018 REGULATION

ACADEMIC YEAR 2018 -2019 (EVEN SEMESTER)

Prepared by
Dr. N. Saravanan,
Associate Professor / IT, KSRCE

1
LIST OF PROGRAMS

1. Compute the GCD of two numbers.

2. Find the square root of a number (Newton’s method)

3. Exponentiation (power of a number)

4. Find the maximum of a list of numbers

5. Linear search and Binary search

6. Selection sort, Insertion sort

7. Merge sort

8. First n prime numbers

9. Multiply matrices

10. Programs that take command line arguments (word count)

11. Find the most frequent words in a text read from a file

12. Simulate elliptical orbits in Pygame

13. Simulate bouncing ball using Pygame

2
INDEX

Ex.
Date Topic Marks Signature
No
1 Compute the GCD of two numbers.

2 Find the square root of a number (Newton’s


method)

3 Exponentiation (power of a number)

4 Find the maximum of a list of numbers

5 Linear search and Binary search

6 Selection sort, Insertion sort

7 Merge sort

8 First n prime numbers

9 Multiply matrices

10 Programs that take command line arguments


(word count)
11 Find the most frequent words in a text read from
a file
12 Simulate elliptical orbits in Pygame

13 Simulate bouncing ball using Pygame

14

15

3
Ex. No: 1

COMPUTE THE GCD OF TWO NUMBERS

AIM:

To write a python program to compute the GCD of two numbers.

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

FIND THE SQUARE ROOT OF A NUMBER (NEWTON’S METHOD)

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 :

def newtonSqrt(n, howmany):


approx = 0.5 * n
for i in range(howmany):
betterapprox = 0.5 * (approx + n/approx)
approx = betterapprox
return betterapprox

print("Newtons Sqrt value is =",newtonSqrt(10, 3))


print("Newtons Sqrt value is =",newtonSqrt(10, 5))
print("Newtons Sqrt value is =",newtonSqrt(10, 10))

SAMPLE INPUT & OUTPUT :

Newtons Sqrt value is = 3.162319422150883


Newtons Sqrt value is = 3.162277660168379
Newtons Sqrt value is = 3.162277660168379

6
RESULT:
Thus the program to find the square root (Newton’s method) is executed and the output is
obtained.

7
Ex. No: 3

EXPONENTIATION (POWER OF A NUMBER)


AIM:

To write a python program to find the exponentiation of a number.

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))

base=int(input("Enter base: "))


exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))

SAMPLE INPUT & OUTPUT :

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

FIND THE MAXIMUM OF A LIST OF NUMBERS


AIM:

To write a python program to find the maximum of a list of numbers.

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])

SAMPLE INPUT & OUTPUT :


Enter number of elements:5
Enter element:1
Enter element:2
Enter element:5
Enter element:6
Enter element:3
Largest element is: 6

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:

To write a python program to perform the linear search.

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 :

Enter the number of elements:5


Enter Element:1
Enter Element:2
Enter Element:3
Enter Element:4
Enter Element:5
Enter number to search: 4
4 found at 4th position

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 :

def binary_sort(sorted_list, length, key):


start = 0
end = length-1
while start <= end:
mid = int((start + end)/2)
if key == sorted_list[mid]:
print("\nEntered number %d is present at position: %d" % (key, mid))
return -1
elif key < sorted_list[mid]:
end = mid - 1
elif key > sorted_list[mid]:
start = mid + 1
print("\nElement not found!")
return -1

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)

x = int(input("\nEnter the number to search: "))


binary_sort(lst, size, x)

SAMPLE INPUT & OUTPUT:

Enter size of list: 6


Enter any number: 8
Enter any number: 7
Enter any number: 4
Enter any number: 1
Enter any number: 2
Enter any number: 5
The list will be sorted, the sorted list is: [1, 2, 4, 5, 7, 8]
Enter the number to search: 7
Entered number 7 is present at position: 4

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)

print('\n\n entered list is:', nlist)


selectionSort(nlist,size)
print('\n\n sorted list is:', nlist)

16
SAMPLE INPUT & OUTPUT:

Enter size of list: 5


Enter any number: 43
Enter any number: 57
Enter any number: 46
Enter any number: 41
Enter any number: 70

entered list is: [43, 57, 46, 41, 70]


sorted list is: [41, 43, 46, 57, 70]

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)

print('\n\n entered list is:', alist)


insertionSort(alist)
print('\n\n sorted list is:', alist)

18
SAMPLE INPUT & OUTPUT:

Enter size of list: 9


Enter any number: 54
Enter any number: 26
Enter any number: 96
Enter any number: 17
Enter any number: 20
Enter any number: 77
Enter any number: 31
Enter any number: 44
Enter any number: 55
entered list is: [54, 26, 96, 17, 20, 77, 31, 44, 55]
sorted list is: [17, 20, 26, 31, 44, 54, 55, 77, 96]

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

while i < len(lefthalf):


alist[k]=lefthalf[i]
i=i+1
k=k+1

while j < len(righthalf):


alist[k]=righthalf[j]
j=j+1
k=k+1
print("Merging ",alist)
alist=[]
n=int(input("Enter No. of Elements:"))

for i in range (0,n):


alist.insert(i,int(input("Enter numbers [%d]:"%i)))

MergeSort(alist)
print(alist)

SAMPLE INPUT & OUTPUT:

Enter No. of Elements:6


Enter numbers [0]:54
Enter numbers [1]:26
Enter numbers [2]:93
Enter numbers [3]:17
Enter numbers [4]:77
Enter numbers [5]:31
Splitting [54, 26, 93, 17, 77, 31]
Splitting [54, 26, 93]
Splitting [54]
Merging [54]

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:

Enter the number: 15


2
3
4
5
7
11
13

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)

SAMPLE INPUT & OUTPUT:


[114, 160, 60]
[74, 97, 73]
[119, 157, 112]

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

FIND THE MOST FREQUENT WORDS IN A TEXT READ FROM A FILE

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 :

fname = input("Enter file name: ")

l=input("Enter letter to be searched:")

k=0

with open(fname, 'r') as f:

for line in f:

words = line.split()

for i in words:

for letter in i:

if(letter==l):

29
k=k+1

print("Occurrences of the letter:")

print(k)

SAMPLE INPUT & OUTPUT:


Input:
Create a file out.txt with the following content:
Contents of file:
hello world hello
hello

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

SIMULATE ELLIPTICAL ORBITS IN PYGAME

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()

screen = pygame.display.set_mode((600, 300))


pygame.display.set_caption("Elliptical orbit")

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)

SAMPLE INPUT & OUTPUT:

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()

size = width, height = 700, 300


speed = [1, 1]
background = 255, 255, 255

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()

SAMPLE INPUT & OUTPUT:

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?

2. What is the purpose of PYTHONPATH environment variable?

3. How Python is interpreted?

4. Is python a case sensitive language?

5. What are the supported data types in Python?

6. What are the built-in type does python provides?

7. What is namespace in Python?

8. What are Python's dictionaries?

37
9. How will you create a dictionary in python?

10. What is Expression?

11. What is module and package 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?

14. What is the purpose of ** operator?

15. What is the purpose is of is operator?

16. How will you randomize the items of a list in place?

38
17. How will you capitalizes first letter of string?

18. What is function?

19. What are the types of function?

20. What is return type?

21. Mention the use of the split function in Python?

22. Explain what is Flash & its benefits?

23. What is File?

24. How to Read the file?

25. How to copy the data from one file to another file?

39

You might also like