Python Programming MANUAL-NEW
Python Programming MANUAL-NEW
LAB MANUAL
FOR
Mission
To prepare the students with high professional skills and ethical values
To impart knowledge through best practices
To instil a spirit of innovation through Training, Research and Development
To undertake continuous assessment and remedial measures
To achieve academic excellence through intellectual, emotional and social stimulation
Vision: To produce the Computer Science and Engineering graduates with the Innovative and
Entrepreneur skills to face the challenges ahead
Mission
M1: To impart knowledge in the state of art technologies in Computer Science and
Engineering
M2: To inculcate the analytical and logical skills in the field of Computer Science and
Engineering
M3: To prepare the graduates with Ethical values to become successful Entrepreneurs
PEO2:Graduates will be able to Gain necessary skills and to pursue higher education for
career growth.
PEO3:Graduates will be able to Exhibit the leadership skills and ethical values in the day
to day life.
PSO1: Graduates should be able to design and analyze the algorithms to develop an Intelligent
Systems
PSO2: Graduates should be able to apply the acquired skills to provide efficient solutions for real
time problems
DO’S
Know the location of the fire extinguisher and the first aid box and how to use them in
case of an emergency.
Read and understand how to carry out an activity thoroughly before coming to the
laboratory.
Use hand sanitizer and face mask before enter in the Laboratory
Report any broken plugs or exposed electrical wires to your lecturer/laboratory technician
immediately.
DONT’S
Do not eat or drink in the laboratory.
Do not open the system unit casing or monitor casing particularly when the power is
turned on. Some internal components hold electric voltages of up to 30000 volts, which can
be fatal.
Do not insert metal objects such as clips, pins and needles into the computer casings. They
may cause fire.
Do not touch, connect or disconnect any plug or cable without your lecturer/laboratory
technician’s permission.
STAFF
S.NO DATE EXPERIMENTS MARKS
SIGNATURE
AIM:
To compute the GCD of two numbers Greatest Common Divisor.
ALGORITHM:
Step1:Start
Step 2: Read two numbers to find the GCD number(x,y)
Step3: def GCD function
Step4: Enter the first number
Step 5: Enter the second number
Step 6: print GCD is x,y
Step 7: Stop
PROGRAM
def gcd_fun (x, y):
if (y == 0): # it divide every number
return x # return x
else:
return gcd_fun (y, x % y)
x =int (input ("Enter the first number: ")) # take first no.
y =int (input ("Enter the second number: ")) # take second no.
num = gcd_fun(x, y) # call the gcd_fun() to find the result
print ("GCD of two number is: ")
print(num) # call num
OUTPUT:
Enter the first number: 54
Enter the second number: 24
GCD of two number is:6
RESULT:
The above program is successfully executed.
AIM:
To find the square root of a number (Newton’s method)
ALGORITHM:
Step1:Start
Step 2: Define the square root function n.
Step 3: Assign the syntax
Step 4: 0.5*(approx root + n/approx root)
Step 5: write the newton’s method square root values
Step 6: Enter the newton’s square root value
Step 7: Run the program
Step 8: Stop
PROGRAM
defnewtonSqrt (n, base):
approx_root = 0.5 * n
fori in range(base):
betterapprox = 0.5 * (approx_root + n/approx_root)
approx_root = betterapprox
returnbetterapprox
print ("the square root of 100:", newtonSqrt (100, 10))
print ("the square root of 256:", newtonSqrt (256, 10))
print ("the square root of 24:", newtonSqrt (24, 10))
OUTPUT:
the square root of 100: 10.0
the square root of 256: 16.0
the square root of 24: 4.898979485566356
RESULT:
The above program is successfully executed.
AIM:
To develop a python programming for exponentiation (power of a number).
ALGORITHM:
Step1:Start
Step 2: Define the number and Exponent
Step 3: Assign the values
Step 4: Give the range of the exponent
Step 5: write the syntax
Step 6: Enter the format of the exponent power values
Step 7: Enter the positive integer
Step 8: Enter the Exponent values
Step 9: Run the program
Step 10: Stop
PROGRAM
number = int (input (" Please Enter any Positive Integer: "))
exponent = int (input (" Please Enter Exponent Value: "))
power = 1
print ("The Result of {0} Power {1} = {2}". format (number, exponent, power))
OUTPUT:
Please Enter any Positive Integer: 3
Please Enter Exponent Value: 4
The Result of 3 Power 4 = 81
RESULT:
The above program is successfully executed.
AIM:
To find a maximum of a list of numbers using python programming.
ALGORITHM:
Step1:Start
Step 2: Enter the lists
Step 3: Using in built method here
Step 4: maxn=0
Step 5: list using loop
Step 6: Enter the Maximum values
Step 7: Run the program
Step 8: Stop
PROGRAM
list1= [10,24,7,54,34,76,21]
maxn=0
if(i>maxn):
maxn=i
OUTPUT:
Maximum number: 76
Maximum number: 76
RESULT:
The above program is successfully executed.
AIM:
To develop a python programming to Selection Sort.
ALGORITHM:
Step 1: Start the program
Step 2: Develop a program for Selection Sort
Step 3: list out the ranges
Step 4: For condition to check the conditions:
for j in range (i + 1, len(alist)):
Step 5: using the syntax
ifalist[j] <alist[smallest]:
Step 6: Select the list of numbers
Step 7: Sorted the entered numbers
Step 8: Execute the program
Step 9: Stop
PROGRAM
defselection_sort(alist):
fori in range (0, len(alist) - 1):
smallest = i
for j in range (i + 1, len(alist)):
ifalist[j] <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: 6 2 4 3 5 1
Sorted list: [1, 2, 3, 4, 5, 6]
RESULT:
The above program is successfully executed.
AIM:
To develop a python programing to Insertion Sort.
ALGORITHM:
Step 1: Start
Step 2: Develop a program for Insertion Sort
Step 3: list out the ranges
Step 4: using While loop check the conditions:
while j >=0 and key <arr[j]:
Step 5: Sort the array
Step 6: Print the array
Step 7: Execute the program
Step 8: Stop
PROGRAM
definsertionSort(arr):
fori in range (1, len(arr)):
key = arr[i]
# Move elements of arr[0..i-1], that are greaterthan key,
#To one position ahead of their current position
j = i-1
while j >=0 and key <arr[j]:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
# main
arr = ['t','u','t','o','r','i','a','l']
insertionSort(arr)
print ("The sorted array is:")
fori in range(len(arr)):
print (arr[i])
RESULT:
The above program is successfully executed.
AIM:
To implement divide and conquer method using Merge Sort.
ALGORITHM:
Step 1: Start
Step 2: Def the required sorting array
Step 3: if merge sort as,
b=c=d=0
Step 4: using While loop for checking the condition:
while b <len(l) and c <len(r):
PROGRAM
defmergeSort(arr):
iflen(arr) > 1:
a = len(arr)//2
l = arr [: a]
r = arr[a:]
mergeSort(l)
mergeSort(r)
b=c=d=0
arr[d] = l[b]
b += 1
else:
arr[d] = r[c]
c += 1
d += 1
while b <len(l):
arr[d] = l[b]
b += 1
d += 1
while c <len(r):
arr[d] = r[c]
c += 1
d += 1
defprintList(arr):
fori in range(len(arr)):
print ()
# Driver program
if __name__ == '__main__':
arr = [0,1,3,5,7,9,2,4,6,8]
MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 16
mergeSort(arr)
printList(arr)
OUTPUT:
Sorted array is:
0123456789
RESULT:
The above program is successfully executed.
AIM:
To find first n prime numbers using python.
ALGORITHM:
Step 1: start
Step 2: Assign the numbers
Step 3: Using if conditions
if(n%i==0):
Step 4: Appear the Break statement
Step 5: using else condition
Step 6: Print the range between the prime number
Step 7: Execute the program
Step 8: Stop
PROGRAM:
numr=int (input ("Enter range:"))
print ("Prime numbers:",end=' ')
for n in range (1, numr):
fori in range (2, n):
if(n%i==0):
break
else:
print (n,end=' ')
OUTPUT:
Enter range:50
Prime numbers: 1 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47
RESULT:
The above program is executed successfully.
AIM:
To Develop a Python program to insert an element into an Array
ALGORITHM:
Step 1: Start
Step 2: Multiplication using Two-dimensional matrix
Step 3: Assign the matrix 1 & matrix 2
Step 4: Using for loop condition to implementing 2-dimensional array
Step 5: using syntax
fori in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
Step 6: Print the value of multiplications
Step 7: Execute the program
Step 8: Stop
PROGRAM
matrix1 = [[12,7,3],
[4 ,5,6],
[7 ,8,9]]
matrix2 = [[5,8,1],
[6,7,3],
[4,5,9]]
res = [[0 for x in range (3)] for y in range (3)]
# explicit for loops
fori in range(len(matrix1)):
for j in range(len(matrix2[0])):
for k in range(len(matrix2)):
# resulted matrix
res[i][j] += matrix1[i][k] * matrix2[k][j]
print (res)
OUTPUT:
[[114, 160, 60], [74, 97, 73], [119, 157, 112]]
RESULT:
The above program is executed successfully.
AIM:
To program that take command line arguments (word count) in python.
ALGORITHM:
Step 1: Start
Step 2: Assign the number of arguments
Step 3: Using argumentsstr(sys.argv)
Step 4: Getting word command line arguments
Step 5: Run the program
Step 6: Stop
PROGRAM
import sys
defword_count(filename):
try:
with open(filename, 'r') as file:
text = file.read()
words = text.split()
returnlen(words)
exceptFileNotFoundError:
print("File not found.")
return -1
if __name__ == "__main__":
iflen(sys.argv) != 2:
print("Usage: python word_count.py <filename>")
sys.exit(1)
filename = sys.argv[1]
count = word_count(filename)
if count != -1:
print("Word count:", count)
OUTPUT:
A module you have imported isn't available at the moment. It will be available soon.
RESULT:
The above program is executed successfully.
AIM:
To find the most frequent words in a text read from a file.
ALGORITHM:
Step 1: Start
Step 2: Frequent words in a text read from a file
Step 3: Give the statement
Step 4: if the program assign the repeated words in text file.
Step 5: Print most repeated words
Step 6: Execute the required program
Step 7: Start to be execute
Step 8: Find the most repeated words in a text file
Step 9: Stop
PROGRAM
OUTPUT:
Themost frequent wordsina textreadfroma file: Frequent
RESULT:
The above program is executed successfully.
AIM:
To simulate elliptical orbits in Pygame.
ALGORITHM:
Algorithm - Simulation of Elliptical orbit
Step 1: Start the program
Step 2: Set screen size and caption
Step 3: Create clock variable
Step 4: Set x and y radius of ellipse.
Step 5: Starting from degree 0 ending with 360 degrees in increments of 10 degrees calculate the (x1, y1)
coordinates to find a point in the elliptical orbit.
Step 6: Convert degree to radians (degree * 2 * math.pi / 360)
Step 7: Set background color, draw center circle, ellipse and another smaller circle on the ellipse
Step 8: Refresh the screen every 5 clock ticks
Step 9: Repeat steps 4 to 8 until user quits the program
Step 10: Stop the program
PROGRAM:
#Elliptical orbits
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()
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))
OUTPUT :
RESULT:
The above program is executed successfully.
AIM:
To simulate bouncing ball using Pygame.
ALGORITHM:
Step 1: Start
Step 2: Set Screen size and caption
Step 3: Create clock variable
Step 4: Starting from degree 0 ending with 360 degrees
Step 5: Set background color, draw center circle, bouncing ball circle at a center
Step 6: Execute the program
Step 7: Stop
PROGRAM
# Program
# Bouncing ball
import sys, pygame
pygame.init()
size = width, height = 700, 250
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:
pygame.time.delay(2)
for event in pygame.event.get():
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()
RESULT:
The above program is executed successfully.
AIM:
Toobject detection using a Tensorflow Python program is to automate the process of identifying and
localizing objects within images or videos.
ALGORITHM:
Object detection using Tensorflow typically involves several steps:
Step1: Data Preparation: Gather and preprocess your dataset.
Step 2: Model Selection: Choose a suitable object detection model.
Step 3: Model Configuration: Configure the selected model according to your needs, such as adjusting
input size, choosing the number of classes to detect, and selecting other hyper parameters.
Step 4: Training: Train your object detection model on your dataset.
Step 5: Evaluation: Evaluate your trained model's performance using the validation set.
Step 6: Fine-tuning (Optional): If necessary, fine-tune your model to improve its performance on specific
types of objects or in specific conditions.
Step 7: Inference: Use your trained model to detect objects in new images or videos.
PROGRAM
(boxes, scores, classes, num_detections) = sess.run(
[boxes, scores, classes, num_detections],
feed_dict={image_tensor: image_np_expanded})
# Visualization of the results of a detection.
vis_util.visualize_boxes_and_labels_on_image_array(
image_np,
np.squeeze(boxes),
np.squeeze(classes).astype(np.int32),
np.squeeze(scores),
category_index,
use_normalized_coordinates=True,
line_thickness=8)
returnimage_np
# Main function
def main():
cap = cv2.VideoCapture(0)
withdetection_graph.as_default():
withtf.Session(graph=detection_graph) as sess:
while True:
ret, image_np = cap.read()
MEC / CSE / 23GES05 - PYTHON PROGRAMMING LAB 27
image_np = detect_objects(image_np, sess, detection_graph)
cv2.imshow('object detection', cv2.resize(image_np, (800, 600)))
if cv2.waitKey(25) & 0xFF == ord('q'):
cv2.destroyAllWindows()
break
if __name__ == '__main__':
main()
OUTPUT :
RESULT:
The above Object detection using Tensorflowprogram is executed successfully.
AIM:
Toobject detection using a Keras Python program is to automate the process of identifying and localizing
objects within images or videos.
ALGORITHM:
Object detection using Keras typically involves several steps:
Step 1: Build an object detection dataset using Selective Search
Step 2: Fine-tune a classification network (originally trained on ImageNet) for object detection
Step 3: Create an object detection inference script that utilizes Selective Search to propose regions
that could contain an object that we would like to detect
Step 4: Use our fine-tuned network to classify each region proposed via Selective Search
Step 5: Apply non-maxima suppression to suppress weak, overlapping bounding boxes
Step 6: Return the final object detection results
PROGRAM
OUTPUT :
RESULT:
The above Object detection using Kerasprogram is executed successfully.