You are on page 1of 30

PYTHON PROGRAMMING LABORATORY

LABORATORY MANUAL

PYTHON PROGRAMMING
CS-506

V SEM (CSE)

DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

DEPARTMENT OF
COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE

This is to certify that Mr./Ms……… ……………………with RGPV EnrollmentNo. ……………………has

satisfactorily completed the course of experiments in …Python Programming….

……………………………………………...………laboratory, as prescribed by Rajiv Gandhi Proudhyogiki

Vishwavidhyalaya, Bhopal for …V…… Semester of the Computer Science and Engineering Department

during year 20…20.… − 21....

Signature of
Faculty In-charge

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

DEPARPTMENT OF COMPUTER SCIENCE &


ENGINEERING
2020-21

LIST OF EXPERIMENTS

Student Name:Madhav Maheshwari Enrollment No.:0832CS181074

Sl. Expt. Name of the Experiment Date Signature


No. No. of of
Cond Faculty-
uction in-Charge

01. 1 Write a Python program to find GCD of two numbers.

Write a Python program to find the square root of a number by Newton’s


02. 2
Method.

03 3 Write a Python program to find the exponentiation of a number.

04 4 Write a Python program to find the maximum from a list of numbers.

05 5 Write a program for implementing linear search.

06 6 Write a program to perform binary search.

07 7 Write a program to perform selection sort.

08 8 Write a program to perform insertion sort.

09 9 Write a program to perform merge sort.

10 10 Write a program to find “first n” prime numbers.

11 11 Write a program to multiply two matrices.

12 12 Write a program for command line arguments.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

13 13 Write a program to find the most frequent words in a text using file handling.

14 14 Write a program to simulate elliptical orbits in “pygame”.

15 15 Write a program to bouncing ball in “pygame”.

EXPT. No. - 1. Write a Python program to find GCD of two numbers.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
Aim: To understand the concept of variables in Python.
Theory: Variable, Python is completely object oriented, and not "statically typed". There is no need t to
declare variables before using them, or declare their type. Every variable in Python is an object.
The highest common factor (H.C.F) or greatest common divisor (G.C.D) of two numbers is the largest positive
integer that perfectly divides the two given numbers. For example, the H.C.F of 12 and 14 is 2.

Program:
def compute_hcf(x,y):
if x >y:
smaller =y
else:
smaller=x
for I in range(1, smaller+1):
if((x%i==0) and (y%i==0)):
hcf=i
return hcf
num1=54
num2=24
print(“The Hcf is “,compute_hcf(num1,num2))
Output
The Hcf is 6

Viva Questions:

1. What is Python?

2. What are the benefits of using Python?

3. Give the difference between Java and Python?

4. How to declare the variable in Python?

5. Python is an interpreted language, justify your answer?

EXPT. No.- 2. Write a Python program to find the square root of a number by Newton’s Method.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

Aim: To understand the concept of decision statements in Python.


Theory: Newton Square Root Method.

Square root expression is rephrased as a parabola that can be optimized via Newtonian optimization. The
same can be applied to higher order roots. Optimal point for this function is the square root for “a”. Let us
implement this in Python.

Program:
def squareRoot(n,1):
x=n
count=0
while(1):
count+=1
root = 0.5*(x+(n/x))
if(abs(root-x)<1):
break
x=root
return root
if_name_==”_main_”:
n=327
l=0.00001
print(squareRoot(n,1))

Output:
18.0831

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
Viva Questions:

1. Explain memory management in Python?

2. What is namespace in Python?

3. What is PYTHON PATH?

4. Define local variables and global variables in Python?

5. Is Python case sensitive?

EXPT. No. - 3. Write a Python program to find the exponentiation of a number.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

Aim: To understand the concept of operator in Python.


Theory: The built-in math module provides a number of functions for mathematical operations. The pow()
method takes a base number and exponent as parameters and returns the power.

Since in Python, there is always more than one way of achieving things calculating power with the
exponentiation operator is also possible. The exponentiation operator x**y evaluates to power.

Program:
import math
print(math.exp(65))
print(math.exp(-6.89))
Output:
1.6948892444103338e+28
0.0010179138409954387
Viva Questions:
1. What is type conversion in Python?
2. Is indentation required in Python?
3. What is the difference between Python Array and List?
4. How to define functions in Python?
5. How can we write comments in Python?

EXPT. No.- 4. Write a Python program to find the maximum from a List of numbers.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

Aim: To understand the concept of List in Python.


Theory: List is fundamental part of most programming languages. It is the collection of elements of a single
data type, e.g. Array of int, Array of string.
However, in Python, there is no native array data structure. So, we use Python lists instead of an array.
Unlike arrays, a single List can store elements of any data type and does everything an array does. We can
store an integer, a float and a string inside the same list. So, it is more flexible to work with.
[10, 20, 30, 40, 50] is an example of what an array would look like in Python, but it is actually a List.
Program:
lis=[]
count=int(input(‘How many numbers?’))
for n in range(count):
number = int(input(‘enter number:’))
lis.append(number)
print(“largest element of the list is :”,max(lis))

Output:
How many number?3
Enter number:8
Enter number:10
Enter number:94
largest element of the list is :94

Viva Questions:
1. Define List Data Structure in Python.
2. Give the difference between List and Tuple.
3. What types of values are contained in the List?
4. Is Python List mutable or not?
5. What are the applications of the List?

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
EXPT. No.- 5. Write a program for implementing linear search.

Aim: To understand the concept of Tuple and while loop in Python.

Theory: In computer science, a linear search or sequential search is a method for finding an element within a
list. It sequentially checks each element of the list until a match is found or the whole list has been searched.
Here is the algorithm:
Step 1: Start
Step 2: Read n elements into the list.
Step 3: Read the element to be searched
Step 4: If a List[pos]==item, then print the position of the item
Step 5: Else increment the position and repeat step 3 until pos reaches the length of the list.
Step 6: Stop
Program:
def linearSearch(array,n,x):
for I in range(0,n):
if(array[i]==x):
return i
return -1
array=[2,4,0,1,9]
x=1
n=len(array)
result=linearSearch(array,n,x)
if(result==-1):
print(“element not found”)
else:
print(“Element found at index”,result)
Output:
Element found at index 3

Viva Questions:
1. Define range() function in Python.
2. How many types of loops available in Python?
3. What is Python Decorators?
4. What is “Pass” in Python?
5. Explain “is” and “is not” in Python.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
EXPT. No. - 6. Write a program to perform binary search.

Aim: To understand the concept of searching technique in Python.


Theory: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering
the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the
interval to the lower half. Otherwise narrow it to the upper half. Repeatedly check until the value is found or
the interval is empty.
Algorithm:
Step 1- Start.
Step 2- Read the search element.
Step 3- Compare the search element with the middle element.
I. if both are matching, print element found.
II. else then check if the search element is smaller or larger than the middle element
Step 4- If the search element is smaller than the middle element, then repeat steps 2 and 3 for the left sub list
of the middle element.
Step 5- Repeat the process until the search element if found in the list.
Step 6- If element is not found, loop terminates.
Step 7- Stop.
Program:
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
if arr[mid] < x:
low = mid + 1
elif arr[mid] > x:
high = mid - 1
else:
return mid

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
return -1
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
# Function call
result = binary_search(arr, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
Output:
Element is present at index 3

Viva Questions:
1. Explain condition statement in Python.
2. How to use “elif” in Python?
3. What is “Doc.” string?
4. What is dictionary in Python?
5. What is a number data type in Python?

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

EXPT. No.- 7. Write a program to perform selection sort.

Aim: To understand the concept of sorting in Python.


Theory: Selection sort algorithm is based on the idea of finding the minimum or maximum element in an
unsorted array and then putting it in its correct position in a sorted array.
The smallest element is selected from the unsorted array and swapped with the leftmost element, and that
element becomes a part of the sorted array. This process continues moving unsorted array boundary by one
element to the right.
Algorithm:
Step 1 – Start.
Step 2 – Set MIN to location 0.
Step 3 − Search the minimum element in the list.
Step 4 − Swap with value at location MIN.
Step 5 − Increment MIN to point to next element.
Step 6 − Repeat until list is sorted.
Step 7 – Stop.

Program:
def selectionSort(array, size):

for step in range(size):


min_idx = step

for i in range(step + 1, size):

if array[i] < array[min_idx]:


min_idx = i

(array[step], array[min_idx]) = (array[min_idx], array[step])

data = [-2, 45, 0, 11, -9]


size = len(data)
selectionSort(data, size)
print('Sorted Array in Ascending Order:')
print(data)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

Output:
Sorted Array in Ascending Order:
[-9, -2, 0, 11, 45]

Viva Questions:
1. What is function in Python?
2. How many types of function in Python?
3. What is the use of append () function?
4. What is “def” keyword in Python?
5. What is lambda function?

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

EXPT. No. - 8. Write a program to perform insertion sort.

Aim: To understand the concept of sorting in Python.


Theory: Insertion sort is a simple sorting algorithm that builds the final sorted array (or list) on the basis of
incremental approach. It is much less efficient on large lists than more advanced algorithms such as quicksort,
heapsort, or merge sort.

Algorithm:

Step 1 – Start.

Step 2 − If it is the first element, it is already sorted and return 1.

Step 3 − Pick next element.

Step 4 − Compare with all elements in the sorted sub-list.

Step 5− Shift all the elements in the sorted sub-list that is greater than the value to be sorted.

Step 6 − Insert the value.

Step 7 − Repeat until list is sorted.

Step 8 – Stop.

Program:

def insertionSort(arr):

for i in range(1, len(arr)):

key = arr[i]

j = i-1

while j >=0 and key < arr[j] :

arr[j+1] = arr[j]

j -= 1

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
arr[j+1] = key

arr = [12, 11, 13, 5, 6]

insertionSort(arr)

print ("Sorted array is:")

for i in range(len(arr)):

print ("%d" %arr[i])

Output:
Sorted array is 5,6,11,12,13

Viva Questions:
1. What is map() function in Python?
2. How to use filter() function in Python?
3. How to use reduce() functions in Python?
4. What is the use of “pass” in Python?
5. What are the iterators in Python?

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

EXPT. No.- 9. Write a program to perform merge sort.

Aim: To understand the concept of sorting in Python.


Theory: Merge sort is a sorting technique based on divide and conquers technique. The worst-case time
complexity of merge sort is Ο(n log n).
Merge sort technique first divides the array into equal halves and then combines them in a sorted manner.
Algorithm:
Merge Sort(arr[], l, r)
If r > l
Step 1-Find the middle point to divide the array into two halves:
Middle m = (l+r)/2
Step 2-Call merge Sort for first half:
Call merge Sort(arr, l, m)
Step 3-Call merge Sort for second half:
Call merge Sort(arr, m+1, r)
Step 4-Merge the two halves sorted in step 2 and 3:
Call merge(arr, l, m, r)
Program:
def merge(arr, l, m, r):
n1 = m - l + 1
n2 = r- m
L = [0] * (n1)
R = [0] * (n2)
for i in range(0 , n1):
L[i] = arr[l + i]
for j in range(0 , n2):
R[j] = arr[m + 1 + j]
# Merge the temp arrays back into arr[l..r]
i=0 # Initial index of first subarray

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
j=0 # Initial index of second subarray
k=l # Initial index of merged subarray

while i < n1 and j < n2 :


if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
# Copy the remaining elements of L[], if there
# are any
while i < n1:
arr[k] = L[i]
i += 1
k += 1
# Copy the remaining elements of R[], if there
# are any
while j < n2:
arr[k] = R[j]
j += 1
k += 1
# l is for left index and r is right index of the
# sub-array of arr to be sorted
def mergeSort(arr,l,r):
if l < r:
# Same as (l+r)//2, but avoids overflow for
# large l and h
m = (l+(r-1))//2

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
# Sort first and second halves
mergeSort(arr, l, m)
mergeSort(arr, m+1, r)
merge(arr, l, m, r)
# Driver code to test above
arr = [12, 11, 13, 5, 6, 7]
n = len(arr)
print ("Given array is")
for i in range(n):
print ("%d" %arr[i]),

mergeSort(arr,0,n-1)
print ("\n\nSorted array is")
for i in range(n):
print ("%d" %arr[i]),

Output:
Given array is
12
11
13
5
6
7

Sorted array is
5
6
7
11
12
13

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
Viva Questions:
1. What is “module” in Python?
2. How to use ternary operators in Python?
3. Explain recursion in Python.
4. What is complex number in Python?
5. What are the local variables and global variables in Python?

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

EXPT. No.- 10. Write a program to find “first n” prime numbers.

Aim: To understand the concept of nested loop in Python.


Theory: A prime number (or a prime) is a natural number greater than 1 that cannot be formed by multiplying
two smaller natural numbers. A number is either divisible by 1 or by number by itself.
Algorithm:
Step 1- First take the number N as input.
Step 2-Then use a for loop to iterate the numbers from 1 to N.
Step 3- Then for checking that the number is prime, divide it by its all previous number. If number is not
divisible by any previous number except 1 and itself, it is a prime number, print it.
Program:
Number = int(input(" Please Enter any Number: "))

print("Prime numbers between", 1, "and", Number, "are:")

for num in range(1, Number + 1):


# all prime numbers are greater than 1
if num > 1:
for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
Output:
Please Enter any Number: 5
Prime numbers between 1 and 5 are:
2
3
5

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
Viva Questions:
1. What is list comprehension?
2. What is slicing in Python?
3. Explain namespace in Python.
4. Define “yield” in Python.
5. Define “unit test” in Python.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

EXPT. No. - 11. Write a program to multiply two matrices.

Aim: To understand the concept of “numpy” in Python.


Theory: Matrix multiplication is an operation that takes two matrices as input and produces single matrix by
multiplying rows of the first matrix to the column of the second matrix. In matrix multiplication make sure that
the number of rows of the first matrix should be equal to the number of columns of the second matrix.

Program:
import numpy as np

# input two matrices


mat1 = ([1, 6, 5],[3 ,4, 8],[2, 12, 3])
mat2 = ([3, 4, 6],[5, 6, 7],[6,56, 7])

# This will return dot product


res = np.dot(mat1,mat2)

# print resulted matrix


print(res)
Output:
[[ 63 320 83]
[ 77 484 102]
[ 84 248 117]]

Viva Questions:
1. What is “numpy” in Python?
2. Explain “generator” in Python.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
3. What is Eigen matrix?
4. Where is “numpy” used?
5. What are the application of “numpy”?

EXPT. No.- 12. Write a program for command line arguments.

Aim: To understand the concept of command line arguments.


Theory: Python supports the creation of programs that can be run on the command line, completely with
command-line arguments. It provides a getopt module, with which command line options and arguments can
be parsed.
Program:
import sys

print(type(sys.argv))
print('The command line arguments are:')
for i in sys.argv:
print(i)
Output:
<class 'list'>
The command line arguments are:
C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py
-f
C:\Users\darkw\AppData\Roaming\jupyter\runtime\kernel-2b1e58d5-d4d8-4bf9-a663-
b783548dbd3d.json

Viva Questions:
1. What is the difference between “Xrange” and “range”?
2. What is “package” in Python?
3. What type casting in Python?
4. What is “constructor” in Python?
5. How to delete a file in Python?

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

EXPT. No. - 13. Write a program to find the most frequent words in a text using file handling.

Aim: To understand the concept of file input/output in Python.


Theory: In this program, we need to find the most repeated word present in given text file. This can be done
by opening a file in read mode using file pointer. Read the file line by line. Split a line at a time and store in an
array. Iterate through the array and find the frequency of each word and compare the frequency with
maxcount. If frequency is greater than maxcount then store the frequency in maxcount and corresponding
word that in variable word.

Program:

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

k=k+1

print("Occurrences of the letter:")

print(k)

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
Output:
Enter file name: out.txt
Enter letter to be searched:o
Occurrences of the letter:
5

Viva Questions:
1. What is file handling in Python?
2. What is data set in Python?
3. How to use “open()” function in Python?
4. What is “pandas” in Python?
5. How to use “close()” function in Python?

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

EXPT. No.- 14. Write a program to simulate elliptical orbits in “pygame”.

Aim: To understand the concept of “pygame” module in Python.


Theory: Pygame is a cross-platform set of Python modules which is used to create video games.
It consists of computer graphics and sound libraries designed to be used with the Python programming
language. Pygame was officially written by Pete Shinners to replace PySDL. Pygame is suitable to create client-
side applications that can be potentially wrapped in a standalone executable.
Program:
import pygame
import math
import sys
pygame.init()
#setting screen size
screen = pygame.display.set_mode((600, 300)) 
#setting caption
pygame.display.set_caption("Elliptical orbit")
#creating clock variable
clock=pygame.time.Clock() 
while(True):
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
# setting x and y radius of ellipse    
    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, 69, 0), [300, 150], 40)
        pygame.draw.ellipse(screen,(255,255,255),[50,50,500,200],1)
        pygame.draw.circle(screen, (0, 255, 0), [x1, y1], 20)
        pygame.display.flip()
        clock.tick(5)# screen refresh rate
Output:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY

Viva Questions:
1. How to use”split” function in Python?

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
2. What is “pygame” module?
3. What is “datetime” in Python?
4. What is pickling and unpickling in Python? ?
5. Explain the “Dogpile” effect.

EXPT. No.- 15 Write a program to bouncing ball in “pygame”.

Aim: To understand the concept of “pygame” module in Python.


Theory: To understand how to implement a bouncing algorithm, it is essential to understand how the
computer controls the trajectory of a sprite (e.g. ball) on the screen. Arcade games are based on a frame
based animation where the screen is refreshed every x milliseconds. Moving sprites are positionned using (x,y)
coordinates and have a velocity vector (Vx,Vy) which specifies the delta in pixels to apply to the (x,y)
coordinates of a sprite between two frames:
frame n:
Sprite Coordinates: (x,y)
frame n+1: Sprite Coordinates: (x+Vx,y+Vy)

Program:
import sys, pygame
pygame.init()
size = width, height = 800, 400
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:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


PYTHON PROGRAMMING LABORATORY
    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()
Output:

Viva Questions:
1. How to use ”init()” function in Python?
2. What is class in python?
3. What is object in python?
4. What is set in python?
5. What is math module in python?

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

You might also like