python program lab manual Updated
python program lab manual Updated
MISSION
To educate students through academic courses and provide knowledge of social and
industrial needs.
To collaborate with leading academic and scientific institutions across the globe to further
enhance education and research.
To motivate young students on a sense of social responsibility through entrepreneurship
and startup.
To be one of the best in the country by developing globally competent engineers motivated
entrepreneurs, prospective researchers, and aspiring academicians.
To strive to set global standards, making our students technologically superior and ethically
strong, who in turn shall contribute to the advancement of society and human kind .
MISSION
To create globally competent students having ability to design, develop and test world class
software, keeping pace with the latest technological developments.
To inculcate the professionalism, team work, innovation and entrepreneurship among the
students.
1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an
engineering specialization to the solution of complex engineering problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex engineering problems reaching
substantiated conclusions using first principles of mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems and design system components
or processes that meet the specified needs with appropriate consideration for the public health and safety, and the
cultural, societal, and environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and research methods including design
of experiments, analysis and interpretation of data, and synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineeringandITtoolsincludingpredictionandmodelingtocomplexengineeringactivitieswith an understanding of the
limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal, health, safety,
legal and cultural issues and the consequent responsibilities relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering solutions in societal and
environmental contexts, and demonstrate the knowledge of, and need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the engineering
practice.
9. Individual and team work: Function effectively as an individual, and as a member or leader in diverse teams, and in
multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the engineering community and
with society at large, such as, being able to comprehend and write effective reports and design documentation, make
effective presentations, and give and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the engineering and management
principles and apply these to one’s own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments
12. Life-long learning: Recognize the need for, and have the preparation and ability to engage in independent and life-
long learning in the broadest context of technological change.
.
PSO 1: Able to identify suitable data structures and algorithms to design, develop and evaluate effective
solutions for real-life and research problems.
PSO 2: Able to excel in various programming/project competitions and technological challenges laid by
professional societies.
CO1: Students will be able to understand the concept of the Greatest Common Divisor
(GCD) of two numbers and the concept of finding the square root of a number using
Newton's method.
CO2: Students will be able to identify and understand the concept of exponentiation,
which involves raising a base number to a given power.
CO3: Students will be able to apply linear search and binary search techniques to search
for specific elements in arrays, lists, or other data structures.
CO4: Students will be able to understand the concept of prime numbers, which are natural
numbers greater than 1 that have no divisors other than 1 and themselves and compare
different prime number generation algorithms in terms of their efficiency and complexity.
CO5: Students will be able to analyze the concept of command line arguments and their
significance in program execution.
CO6: Students will be able to develop critical thinking skills by analyzing and improving
the accuracy, performance, and visual representation of the simulated elliptical orbits.
Clean up after yourself and keep your workspace tidy. Report any maintenance
issues or concerns to the lab staff promptly.
SAFETY PRECAUTIONS
All staff, students and others who work in laboratory must understand and agree to the information in this
document. All procedures which need to be conducted alone or after-hours need to be reviewed for hazards
and must be
Turn off the machine once you are done using it.
Do not plug in external devices without scanning them for computer viruses.
Ensure that the temperature in the room stays cool, since there are a lot of machines inside a lab
as these can overheat easily. This is one of the many ways of ensuring computer safety.
Try not to touch any of the circuit boards and power sockets when a device is connected to them
and switched on.
CONTENTS
SL
NAME OF THE EXPERIMENTS PAGENO.
NO
Compute the GCD of two numbers. 12-13
1
Find the square root of a number (Newton's method) 14-15
2
Find the Exponentiation (power of a number) 16-17
3
Find the maximum of a list of numbers 18-19
4
Linear search and Binary search. 20-22
5
Selection sort, Insertion sort 23-24
6
Merge sort. 25-26
7
First n prime numbers. 27-28
8
Multiply matrices. 29-30
9
Programs that take command line arguments (word count) 31-32
10
Find the most frequent words in a text read from a file 33-34
11
Simulate elliptical orbits in Pygame. 35-36
12
Simulate bouncing ball using Pygame. 37-38
13
3. Exponentiation
(power of a number).
9. Multiply matrices
PRACTICAL/SESSIONALEVALUTIONSCHEME
Evaluation Scheme
Attendance &Daily performance 20
Lab Record 20
Lab Viva 10
Final Experiment &Viva 50
Total 100
Experiment -1
AIM OF THE EXPERIMENT: Compute the GCD of two numbers
Requirement Specification:
Installation of Python in System
Pen and paper
Calculator (optional)
Two numbers to compute their GCD
THEORY:
The objective of this laboratory experiment is to compute the Greatest Common
Divisor (GCD) of two given numbers using the Euclidean algorithm.
PROCEDURE
Write down the two numbers whose GCD is to be computed.
Apply the Euclidean algorithm by performing the following steps:
a. Divide the larger number by the smaller number.
b. Write down the remainder obtained.
c. Replace the larger number with the smaller number and the smaller number
with the remainder obtained in step b.
d. Repeat steps a-c until the remainder obtained is zero.
The GCD of the two numbers is the last non-zero remainder obtained in step 2.
Program development:
#Python Program to find GCD of Two Numbers a temp variable
num1=int (input())
num2= int (input() )
a=num1
b=num2
while(num2!=0):
#swap using temp variable
INPUT:
15
75
OUTPUT:
15
CONCLUSION:
The Euclidean algorithm is a simple and efficient method for computing the GCD of
two numbers. It is widely used in various applications such as cryptography, number
theory, and computer science. By following the above procedure, anyone can
compute the GCD of two numbers with ease.
EXPERIMENT- 2
EXPERIMENT -3
AIM OF THE EXPERIMENT: Exponentiation (power of a number).
Requirement Specification:
Installation of Python in System
Scientific calculator
Pen and paper
Stopwatch or timer
THEORY:
Exponentiation, or the process of raising a number to a power, is a fundamental
mathematical operation that is used extensively in various fields of science and
engineering. In this experiment, we will investigate the relationship between
exponentiation and the power of a number. Specifically, we will explore how the
power of a number changes as the exponent is varied.
PROCEDURE
Choose a base number. For the purposes of this experiment, we will use 2 as the
base number.
Calculate the power of the base number for each exponent using the formula:
Power = base number ^ exponent
Graph the data on a coordinate plane, with the exponent on the x-axis and the
power on the y-axis.
Compare the rate of change to the value of the base number. For a base
number of 2, the rate of change should be equal to 2.
Repeat the experiment with different base numbers and observe any
differences in the results.
Program development:
num=int (input(“Enter number:”))
exp-int (input("Enter exponential value: "))
result=1
for i in range(1,exp+1):
result=result*num
print("Result is:",result)
Output:-
Enter number:2
Enter exponential value:10
Result is :1024
CONCLUSION:
EXPERIMENT- 4
AIM OF THE EXPERIMENT: Programs on Loops.
Requirement Specification:
Computer with a programming language installed (e.g. Python,)
Stopwatch or timer
Pen and paper
THEORY:
Loops are a fundamental programming construct that allows a program to repeat a set of
instructions multiple times. In this experiment, we will investigate the efficiency of different types
of loops in terms of their execution time and memory usage.
PROCEDURE
Choose a programming language and create three different programs that accomplish the
same task using a while loop, a for loop, and a do-while loop. For example, the task could be
to sum the first 1000 natural numbers.
Repeat step 3 multiple times and calculate the average execution time for each program.
Calculate the memory usage of each program using a memory profiler. Record the memory
usage in the table.
Compare the efficiency of each program in terms of execution time and memory usage.
Program development:
Output:-
Enter number of element in list 5
Enter elements of the list
12
32
45
67
87
Maximum of the list is :
87
CONCLUSION:
This experiment demonstrates the trade-offs between different types of
loops in terms of their efficiency. While a do-while loop may be more
efficient in terms of execution time, it may use more memory than a while
loop. Similarly, a for loop may be less efficient in terms of execution time
than a while loop, but it may use less memory. By understanding these
PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
18
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
trade-offs, programmers can choose the most appropriate loop for a given
task to optimize the performance of their programs.
EXPERIMENT -5
Create arrays of different sizes (e.g. 100, 1000, 10000, 100000) and
populate them with random numbers.
Run each program on each array and record the execution time in a
Repeat step 4 multiple times and calculate the average execution time
for each program.
Graph the data on a coordinate plane, with the size of the array on the
x-axis and the execution time on the y-axis.
Program development:
def Linear search (array,n,k):
for j in range (0,n);
if (array[j]==k):
return j
return -1
array=[1,3,5,7,9,]
k=7
n=len(array)
result=Linear search (array,n,k)
if(result== -1):
print(“Element found at index: “,result)
Output:-
Element found at index: 3
CONCLUSION:
EXPERIMENT- 6
AIM OF THE EXPERIMENT: Selection sort, Insertion sort
Requirement Specification:
Python installed on a computer
Stopwatch or timer
Pen and paper
THEORY:
Sorting is a fundamental operation in computer science, and there are
many algorithms for sorting data. In this experiment, we will compare the
efficiency of two commonly used sorting algorithms in Python: selection
sort and insertion sort.
PROCEDURE
Create a Python program that implements selection sort and another
program that implements insertion sort. The programs should sort a
list of integers in ascending order.
Run each program on each list and record the execution time in a
table.
Graph the data on a coordinate plane, with the size of the list on the x-
axis and the execution time on the y-axis.
Program development:
def selection sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[i] <alist[smallest]:
smallest =j
alist[i], alist[smallest]=alist[smallest), alist[i]
alist=input("Enter the list of numbers: ').split()alist [int(x) for x in alist]
selection_sort(alist)
print("Sorted list: ', end=")
print(alist)
Output:-
Enter the list of numbers:142368975
Sorted list:[1,2,3,4,5,6,7,8,9]
6.b.
CONCLUSION:
This experiment demonstrates the efficiency differences between selection
sort and insertion sort algorithms in Python. While insertion sort may be
faster for small lists, selection sort is more efficient for larger lists. By
understanding the performance characteristics of different sorting
algorithms, programmers can choose the most appropriate algorithm for a
given task to optimize the performance of their programs.
EXPERIMENT- 7
AIM OF THE EXPERIMENT: Merge sort
Requirement Specification:
Python installed on a computer
Stopwatch or timer
Pen and paper
THEORY:
Sorting is a fundamental operation in computer science, and there are many
algorithms for sorting data. In this experiment, we will compare the
efficiency of merge sort algorithm in python.
PROCEDURE
Create a Python program that implements Merge sort algorithm. The
program should sort a list of integers in ascending order.
Run the program on each list and record the execution time in a table.
Repeat step 4 multiple times and calculate the average execution time
for each program.
Graph the data on a coordinate plane, with the size of the list on the x-
axis and the execution time on the y-axis.
CONCLUSION:
This experiment demonstrates the efficiency of Merge sort algorithm in
Python. Merge sort is one of the most efficient sorting algorithms in terms
of execution time and is particularly useful for large lists. By
understanding the performance characteristics of different sorting
algorithms, programmers can choose the most appropriate algorithm for a
given task to optimize the performance of their programs.
EXPERIMENT -8
AIM OF THE EXPERIMENT:. First n prime numbers
Requirement Specification:
Python installed on a computer
Pen and paper
THEORY:
Prime numbers are an important mathematical concept and are often used
in computer science. In this experiment, we will write a Python program to
generate the first n prime numbers.
PROCEDURE
Define a function called is_prime(num) that takes an integer num as
input and returns True if num is a prime number and False otherwise.
Test the program with small values of n (e.g. 10, 20, 50) and verify
that it generates the correct list of prime numbers.
Graph the data on a coordinate plane, with the value of n on the x-axis
and the execution time on the y-axis.
PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
28
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
Program development:
#change the values of lower and upper for a different result
Lower=int(input(“Enter number starting:”))
Upper=int(input(“Enter number ending:”))
Print(“prime numbers between”,lower,”and”,upper,”are:”)
For num in range (lower,upper,+1):
#prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i)=0:
break
else:
print(num)
Output:-
Enter number starting :1
Enter number ending:9
Prime numbers between 1 and 9 are:
2
3
5
7
CONCLUSION:
EXPERIMENT -9
AIM OF THE EXPERIMENT: Multiply two matrices using nested
loops
Requirement Specification:
Python installed on a computer
Pen and paper
THEORY:
Matrix multiplication is an important mathematical operation in computer science.
In this experiment, we will write a Python program to multiply two matrices using
nested loops.
PROCEDURE
Define two matrices A and B of size m x n and n x p, respectively. Initialize the
matrices with random values.
Implement the matrix multiplication algorithm using nested loops. Record the
execution time for different matrix sizes.
Analyze the performance of the program for different matrix sizes. Record the
execution time for each matrix size.
Graph the data on a coordinate plane, with the size of the matrices on the x-axis
Program development:
#take a 3x3 matrix
A=[[12,7,3],
[4,5,6],
[7,8,9]]
#take a 3x4 matrix
B=[[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
result=[[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
# iterating by row of A
for i in range(len(A)):
# iterating by column by B
for j in range(len(B[0])):
# iterating by rows of B
for k in range(len(B));
result[i][j]+=A[i][k]*B[k][j]
for r in result:
print(r)
output:
[114,160,60,27]
EXPERIMENT- 10
Implement the word count algorithm. The program should open the
file and count the number of words in it. The word count should be
Test the program with different text files and verify that it correctly
counts the number of words in each file.
Analyze the performance of the program for large text files. Record
the execution time for each file size.
Graph the data on a coordinate plane, with the size of the text file on
the x-axis and the execution time on the y-axis.
Program development:
import sys
print (“This is the name of the script”, sys.argv[0])
printf(“Number of arguments :”,len(sys.argv))
printf(“The arguments are :”,str(sys.argv))
#Example output
#This is the name of the script:sysargv.py
#Number of arguments in :3
#The arguments are:[‘sysargv.py’,’arg1’,’arg2’]
output:
This is the name of the script: sysargv.py
Number of arguments: 3
The arguments are: ['sysargv.py', 'arg1', 'arg2']
CONCLUSION:
EXPERIMENT- 11
Implement the word count algorithm. The program should open the
file, read the text, split the text into words, and count the frequency of
each word.
Test the program with different text files and verify that it correctly
identifies the most frequent words in each file.
Analyze the performance of the program for large text files. Record
the execution time for each file size.
Graph the data on a coordinate plane, with the size of the text file on
the x-axis and the execution time on the y-axis.
Program development:
Import sys
Count={}
With open (sys.argv[1],’r’)as f:
For line in f :
For word in line .spilt():
if word not in count:
count[word]=1
else:
count[word]+=1
print(word,count[word])
PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
35
RAAJDHANI ENGINEEERING COLLEGE (B-Tech), BHUBANESWAR
PROBLEM SOLVING AND PYTHON PROGRAMMING
file.close()
output:
hello 1
world 1
this 1
is 1
a2
test 2
file 2
CONCLUSION:
This experiment demonstrates the efficiency of identifying the most
frequent words in a text file using Python. The program we created is able
to efficiently identify the most frequent words in a text file using Python.
By understanding the performance characteristics of different algorithms,
programmers can choose the most appropriate algorithm for a given task
to optimize the performance of their programs. This program can be used
in a wide range of applications such as language modeling, sentiment
analysis, and more.
EXPERIMENT- 12
AIM OF THE EXPERIMENT: Simulate elliptical orbits in pygame
Requirement Specification:
Installation of Python in System
Pygame module installed on the computer
THEORY:
Pygame is a popular Python module used for game development. In this
experiment, we will use Pygame to simulate elliptical orbits of planets
around a star. We will use Kepler's laws of planetary motion to model the
orbits and Pygame to visualize the motion of the planets.
PROCEDURE
Define the basic elements of the simulation, including the star, the
planets, and their initial positions and velocities.
Define a function to draw the planets and star on the screen using
Pygame.
Test the simulation with different initial conditions and verify that the
orbits of the planets are elliptical.
CONCLUSION:
EXPERIMENT- 13
AIM OF THE EXPERIMENT: Simulate bouncing ball using pygame
Requirement Specification:
Python 3.x
Pygame library
THEORY:
Simulate a bouncing ball using Pygame.
PROCEDURE
Import the Pygame library and initialize it.
Set the screen size and caption.
Set the initial position, size, and velocity of the ball.
Create a game loop that updates the position of the ball and redraws it
on the screen.
Add collision detection to make the ball bounce off the walls.
Add gravity to make the ball fall and bounce realistically.
Run the game loop until the program is stopped.
Program development:
import pygame
pygame.init()
class Ball(pygame.sprite.Sprite):
def __init__(self, screen, background):
pygame.sprite.Sprite.__init__(self)
self.screen = screen
self.background = background
self.image = pygame.Surface((30, 30))
self.image.fill((255, 255, 255))
pygame.draw.circle(self.image, (0, 0, 255), (15, 15), 15)
self.rect = self.image.get_rect()
self.rect.center = (320, 240)
self.dx = 5
self.dy = 5
def update(self):
old_center = self.rect.center
self.rect.centerx += self.dx
self.rect.centery += self.dy
pygame.draw.line(self.background, (0, 0, 0), old_center,
self.rect.center)
self.check_bounds()
def check_bounds(self):
"""Bounce on encountering any screen boundary"""
if self.rect.right >= self.screen.get_width() or self.rect.left <= 0:
self.dx *= -1
if self.rect.bottom >= self.screen.get_height() or self.rect.top <= 0:
self.dy *= -1
def main():
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Boundary-checking: bounce")
background = pygame.Surface(screen.get_size())
if __name__ == "__main__":
main()
output:
A Pygame window is opened with the title "Boundary-checking: bounce."
The window is 640 pixels wide by 480 pixels tall. A white background is
drawn on the window, and a blue ball is drawn in the center of the
window. The ball moves across the screen at a constant speed of 5 pixels
per frame, bouncing off the top, bottom, left, and right boundaries of the
window when it reaches them.
CONCLUSION: