Python Lab Manual
Python Lab Manual
Python Lab Manual
LAB MANUAL
CS-506: Python Lab
CEO2 To Design and analyze python looping, control statements and string
manipulations.
CEO3 To learn and understand to create and manipulate strings, lists, tuples and
dictionaries
CEO4 To Analyze and use of different libraries like Numpy and Pandas
CEO5 To learn file handling like CSV, JSON and other file format .
Course Outcomes
Upon completion of this subject / course the student will be able:
CO1 Understand Python syntax and semantics and be fluent in the use of Python flow
control and Functions
CO2 Define and demonstrate the use of built-in data structures and Control
Structures
CO3 Identify the methods to create and manipulate strings, lists, tuples and dictionaries.
CO4 Define and demonstrate different functions of Numpy and Panda Library.
CO5 Determine the need for scraping websites and working with CSV, JSON and other file
formats.
CS-506: Python lab
List of Programs:
https://www.kaggle.com/datasets/utkarsharya/ecommerce-purchases
https://www.kaggle.com/datasets/kaggle/sf-salaries
https://www.kaggle.com/datasets/wenruliu/adult-income-dataset
https://www.kaggle.com/c/titanic
https://www.kaggle.com/datasets/lava18/google-play-store-apps
Algorithm:
Euclidean Algorithm to find the GCD of two numbers.
1. Begin
2. if a = 0 OR b = 0, thenreturn 0
3. if a = b, thenreturn b
4. if a > b, then
5. return GCD(a-b, b)else
6. return GCD(a, b-a)
7. End
2.To write a Python Program to find the square root of a number by Newton’s
Method.
Newton's method, also known as the Newton–Raphson method, named after Isaac Newton and Joseph
Raphson, is a root-finding algorithm which produces successively better approximations to the roots (or
zeroes) of a real-valued function.
Algorithm:
Algorithm:
(x -> Number , y-> exponent )
17. Assign x to a temporary variable(say n).
18. Loop y times; each time assigning x=n*x.
19. Return the value of x (which is x to the power y).
4. To write a Python Program to find the maximum from a list of numbers.
Algorithm:
i. Create a variable m.
ii. Assign it the most negative no. (for instance -1000000000).
iii. Now iterate through the list (L). Each time comparing the value of m with L[i].
iv. If L[i]>m then
v. assign m = L[i]
vi. Now print the value of m.
5. To write a Python Program to perform Linear Search.
Linear search is a sequential searching algorithm where we start from one end and check every
element of the list until the desired element is found. It is the simplest searching algorithm.
Algorithm
i. Start
ii. set i=0
iii. While i<size
iv. If Ar[i]==item
v. Return i and goto step 5
vi. End If
vii. Set i=i+1
viii. End While
ix. Return -1.
x. Stop.
6. To write a Python Program to perform binary search.
Binary Search is a searching algorithm for finding an element's position in a sorted array. In this approach,
the element is always searched in the middle of a portion of an array.
Note: Binary search can be implemented only on a sorted list of items. If the elements are not sorted
already, we need to sort them first.
Algorithm
i. Start
ii. Set Low =0
iii. Set High= Size-1
iv. While Low<=High
v. set Mid=(Low+High)/2
vi. If Item=Ar[Mid]
vii. Return Mid and goto step
viii. Else If Item <Ar[Mid]
ix. High=Mid-1
x. Else
xi. Low=Mid+1
xii. End If
xiii. End While
xiv. Return -1
xv. Stop.
7. To write a Python Program to perform selection sort.
Selection sort is a simple sorting algorithm. This sorting algorithm is an in-place comparison-based
algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted
partat the right end. Initially, the sorted part is empty and the unsorted part is the entire list.
Algorithm:
i. Set MIN to location 0
ii. Search the minimum element in the list
iii. Swap with value at location MIN
iv. Increment MIN to point to next element
v. Repeat until list is sorted
8. To write a Python Program to perform insertion sort.
Insertion sort is a sorting algorithm that places an unsorted element at its suitable place in each
iteration. Insertion sort works similarly as we sort cards in our hand in a card game. We assume that the
first card is already sorted then, we select an unsorted card.
Algorithm:
i. If it is the first element, it is already sorted. return 1;
ii. Pick next element
iii. Compare with all elements in the sorted sub-list
iv. Shift all the elements in the sorted sub-list that is greater than the value to be sorted
v. Insert the value
vi. Repeat until list is sorted
9. To write a Python Program to perform Merge sort.
Merge sort is a sorting algorithm based on the Divide and conquer strategy. It works by recursively
dividing the array into two equal halves, then sort them and combine them. It takes a time of (n logn) in
the worst case.
Algorithm:
1: Find the middle index of the array.
Middle = 1 + (last – first)/2
2: Divide the array from the middle.
3: Call merge sort for the first half of the
arrayMergeSort(array, first, middle)
4. Call merge sort for the second half of the
array.MergeSort(array, middle+1, last)
5. Merge the two sorted halves into a single sorted array.
10. To write a Python program to find first n prime numbers.
Algorithm:
1. Start
2. Set ct =0, n =0, i= 1, j=1
3. Repeat 4 to 12 Until n<104. j =1
4. ct =0
5. Repeat Step 7 to 9 Until j<=i
6. if i%j==0 then
7. ct = ct+19. j =j+1
8. if ct==2 then PRINT i
9. n =n+1
10. i = i+1
11. End
11. To write a Python program to multiply matrices.
The sys module provides functions and variables used to manipulate different parts of the Python
runtime environment. This module provides access to some variables used or maintained by the
interpreter and to functions that interact strongly with the interpret er.
One such variable is sys.argv which is a simple list structure. It’s main purpose are:
It is a list of command line arguments.
len(sys.argv) provides the number of command line arguments.
sys.argv[0] is the name of the current Python script.
13. To write a Python program to find the most frequent words in a text read from
a file.
Python provides inbuilt functions for creating, writing, and reading files. Two types of files can be
handled in python, normal text files, and binary files (written in binary language,0s and 1s).
1. Text files: In this type of file, Each line of text is terminated with a special character called
EOL (End ofLine), which is the new line character (‘\n’) in python by default.
2. Binary files: In this type of file, there is no terminator for a line, and the data is stored after
converting it into machine-understandable binary language.
Here we are operating on the .txt file in Python. Through this program, we will find the most repeated
word in a file.
Algorithm:
1. Variable maxCount will store the count of most repeated word.
2. Open a file in read mode using file pointer.
3. Read a line from file. Convert each line into lowercase and remove the punctuation marks.
4. Split the line into words and store it in an array.
5. Use two loops to iterate through the array. Outer loop will select a word which needs to be count.
Inner loop will match the selected word with rest of the array. If match found, increment count by 1.
6. If count is greater than maxCount then, store value of count in maxCount and corresponding word
in variable word.
7. At the end, maxCount will hold the maximum count and variable word will hold most repeated word.
14. To write a Python program to simulate elliptical orbits in Pygame.
Algorithm:
1. Define the class Solar system and initialize all the child classes under it.
2. Define the class for Sun and initialize all the attributes it takes as input
3. Define the planet class and provide details of all the various planets and their attributes
4. End the program with source code .
15. To write a Python program to bouncing ball in Pygame.
Algorithm:
1. Start
2. Set screen size and background color.
3. Set speed of moving ball.
4. Create a graphical window using set_mode()
5. Set caption
6. Load the ball image and create a rectangle area covering the image
7. Use blit() method to copy the pixel color of the ball to the screen
8. Set background color of screen and use flip() method to make all images visible.
9. Move the ball in specified speed.
10. If ball hits the edges of the screen reverse the direction.
11. Create an infinite loop and Repeat steps 9 and 10 until user quits the program
12. Stop.
Numpy & Pandas
1. Create a dataframe where columns are :- SNo, Name, Enrollment, Mobile and
insert 5columns in it.
Solu: The required program is :-
import pandas as pd
data= {'SNo':[1,2,3,4,5],'Name':['A','B','C','D','E'],'Enroll':[101,102,103,104,105],
'Mobile':[123456789,234567891,345678912,456789123,567891234]}
df = pd.DataFrame(data)
print(df)
2. Create a dataframe where columns are :- Student name, MST1 and MST2. Insert
10 rows and apply different operations on it.
Solu: The required program is :-
import pandas as pd
d={ 'Name':pd.Series(['A','B','C','D','E','F','G','H','I','J']),
'MST1':pd.Series([10,15,12,13,10,8,20,19,15,13]),
'MST2':pd.Series([15,16,13,18,19,20,10,5,18,10])
}
df = pd.DataFrame(d)print(df.describe())
3. Create a dataframe where columns are student name, MST1 and MST2 .Insert 10
rows and apply different operations on it.
1 roll =pd.Series([1,2,3,4,5,6,7,8,9,10])
2 name =pd.Series(['A','B','C','D','E','F','G','H','I','J'])
3 mst1 =pd.Series([10,20,30,40,10,15,12,13,17,25])
4 mst2 =pd.Series([10,20,30,40,10,15,12,13,17,25]) In [10]:
1S =pd. DataFrame({ 'roll': roll , 'name' : name, 'mst1' : mst1, 'mst2' : mst2})
3. Create a dataframe where columns are student name, MST1 and MST2 .Insert 10
rows and apply Sorting operations on it.
Solu: The required program is :-
df = pd.DataFrame({'Name':['A','D','C','B','J','K','P','H','G','U'],'MST1':[10,15,12,14,9,13,20,14,
10,11],'MST2':[13,12,9,8,16,17,19,20,7,18]})
import numpy as np
A = np.array([[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16],[17,18,19,20]])
import numpy as np
A = np.array([[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]])
import numpy as np
A = np.array([[0,0,0,0,0,0,0,0],
[1,1,1,1,1,1,1,1],
[0,0,0,0,0,0,0,0],
[1,1,1,1,1,1,1,1],
[0,0,0,0,0,0,0,0],
[1,1,1,1,1,1,1,1]])
y = 2*x+3 plt.plot(x, y)
plt.grid()plt.show()
8. Plot Bar Graph between x and y array.
Solu: The required program is :-
import pandas as pd
df = pd.read_excel("Student.xlsx")print(df)
10. Sort dataframe in ascending order.
Solu: The required program is :-
import pandas as pd
df = pd.read_excel("Student.xlsx")
df=df.sort_values("Marks")print(df)
11. Find max, min, mean value in dataframe.
import pandas as pd
df = pd.read_excel("Student.xlsx")maxx = df['Marks'].max()
minn = df['Marks'].min()
mean = df['Marks'].mean() print('Maximum marks : ',maxx)print('Minimum marks :
',minn)print('Average marks : ',mean)