Python Lab Exercises for B.Sc. Students
Python Lab Exercises for B.Sc. Students
7th Semester
Year/Semester 4/7
1. Introduction to Python
2. Variables and operations in Python
3. Control structures and loops in Python
4. Functions in Python
5. Data Structures in Python
6. Data analysis using NumPy in Python
7. Plots using Matplotlib in Python
Name: Sakshi Tomar Roll Number: 22MPBS407016
Index Sheet
Introduction to Python
1
Functions in Python
4
10
Laboratory 1
Title of the Laboratory Exercise: Introduction to Python
3. Experimental Procedure
Students are given a set of Python programs. Write and execute Python programs using
Python command line
Command prompt from windows
4. Calculations/Computations/Algorithms
import math
print("sin(pi/6) =", [Link]([Link]/6))
print("cos(pi) =", [Link]([Link]))
print("tan(pi/2) =", [Link]([Link]/2))
print("sec(1) = 1/cos(1) =", 1/[Link](1))
print("e^3 =", math.e**3)
Name: Sakshi Tomar Roll Number: 22MPBS407016
5. Presentation of Results
4) Printing Statements
i. hello, world!
Hi from india
ii. I am running python for the first time
Evaluation of Powers
4 i) 3 = 729
(−2) = −32
153 = 4.27 × 10
(−5) = 0.0016
ii) Quotient and Remainder
For 92739232973 ÷ 17:
o quotient = 5455248998
o remainder = 7
For 123231321321 ÷ 11:
o quotient = 11202847392
o remainder = 9
iii) Absolute Value of Complex Numbers
∣ 3 + 4𝑖 ∣= 5
∣ 43 − 22𝑖 ∣= √43 + 22 = 48.108
iv) Enter any number: 12.5
The class of the given number is: <class 'float'>
v) Enter an integer: 4
As float = 4.0
Enter a float number: 3.2
As int = 3
vi) Factorials
7! = 5040
9! = 362880
11! = 39916800
13! = 6227020800
15! = 1307674368000
Name: Sakshi Tomar Roll Number: 22MPBS407016
sec (1) = ( )
≈ 1.8508
𝑒 ≈ 20.085
ln (19) ≈ 2.944
Laboratory 2
Title of the Laboratory Exercise: Variables, operators and expressions
Aim
To develop programs using variables of basic data types and compute simple
expressions involving operators
Objectives
At the end of this lab, the student will be able to
Use variables of the basic data types
Apply various operators in expressions
Create Python programs to solve simple numeric problems
3. Experimental Procedure
i. Analyse the problem statement
ii. Design an algorithm for the given problem statement and develop a
flowchart/pseudo-code
iii. Implement the algorithm in Python language
iv. Execute the Python program
v. Test the implemented program
vi. Document the Results
vii. Analyse and discuss the outcomes of the experiment
Name: Sakshi Tomar Roll Number: 22MPBS407016
4. Questions
# Rectangle
l = float(input("\nEnter length of the rectangle: "))
w = float(input("Enter width of the rectangle: "))
area_rect = l * w
perimeter_rect = 2 * (l + w)
5. Presentation of Results
Time = 3.0
Area of rectangle = 50
Perimeter of rectangle = 30
Name: Sakshi Tomar Roll Number: 22MPBS407016
In this experiment, Python was used to perform basic mathematical operations such as
swapping numbers, calculating simple interest, and finding the area and circumference of a circle.
7. Conclusions
The experiment successfully demonstrated the use of Python for solving simple mathematical
problems
Laboratory 3
Title of the Laboratory Exercise: Control structures in Python
3. Experimental Procedure
i. Analyse the problem statement
ii. Design an algorithm for the given problem statement and develop a
flowchart/pseudo-code
iii. Implement the algorithm in Python language
iv. Execute the Python program
v. Test the implemented program
vi. Document the Results
vii. Analyse and discuss the outcomes of the experiment
4. Questions
a. Write a program to find greatest of three numbers
a = int(input("Enter first number: "))
Name: Sakshi Tomar Roll Number: 22MPBS407016
x, y = y, x
print("After interchange:")
print("x =", x)
print("y =", y)
c. Write a program to accept a list of integers and display the smallest and largest
element in the list without using the built in function
n = int(input("How many integers do you want to enter? "))
lst = []
for i in range(n):
num = int(input(f"Enter number {i+1}: "))
[Link](num)
smallest = lst[0]
largest = lst[0]
for x in lst[1:]:
if x < smallest:
smallest = x
if x > largest:
largest = x
print("Smallest element =", smallest)
print("Largest element =", largest)
Name: Sakshi Tomar Roll Number: 22MPBS407016
if guess == secret:
print("Correct! You've guessed the secret number.")
else:
print("Wrong guess. Try again!")
f. Write a Python program to check if a passenger has a valid ticket and baggage within
limit
ticket = input("Do you have a valid ticket? (yes/no): ")
baggage = float(input("Enter baggage weight in kg: "))
print("Grade B")
elif marks >= 40:
print("Grade C")
else:
print("Fail")
h. Programs to demonstrate while loop
i=1
while i <= 5:
print("Number:", i)
i += 1
i. Write a Python program that uses a for loop to print numbers from 0 to given any
number
n = int(input("Enter a number: "))
for i in range(n + 1):
print(i)
j. Write a Python program using a while and for loop to find the factorial of a number
i)
n = int(input("Enter a number: "))
fact = 1
i=1
while i <= n:
fact *= i
i += 1
print("Factorial =", fact)
ii)
n = int(input("Enter a number: "))
fact = 1
for i in range(1, n+1):
fact *= i
print("Factorial =", fact)
k. Write a Python program using nested for loops to print the products of numbers from
1 to 10 in a grid format
for i in range(1, 11):
for j in range(1, 11):
print(i * j, end="\t")
Name: Sakshi Tomar Roll Number: 22MPBS407016
print()
l. Write a Python program that finds the integer square root of a number if it is a perfect
square; otherwise, it should print that number
n = int(input("Enter a number: "))
root = int(n ** 0.5)
if root * root == n:
print("Integer square root:", root)
else:
print(n, "is not a perfect square")
5. Presentation of Results
b) Enter value of x: 10
Enter value of y: 20
After interchange:
x = 20
y =10
c) How many integers do you want to enter? 5
Enter number 1: 12
Enter number 2: -3
Enter number 3: 45
Enter number 4: 0
Enter number 5: 8
Smallest element = -3
Largest element = 45
Name: Sakshi Tomar Roll Number: 22MPBS407016
Using * : HelloHelloHello
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
l) Enter a number: 49
the experiment showed how Python can take user input using the input() function and process
the values through conditions and loops.
The decision-making using if-elif-else accurately determined the greatest of three numbers and
the student’s grade. Loops helped in reading multiple subject marks and list elements, and string
slicing made digit reversal simple. The smallest–largest program showed how comparisons work
without built-in functions. The odd-number program demonstrated conditional termination when
a specific value (14) is reached.
7. Conclusions
From this practical, We learned how to read values from the user and apply conditions, loops, and
basic logic to solve real-time problems.
Laboratory 4
Title of the Laboratory Exercise: Functions
3. Experimental Procedure
i. Analyse the problem statement
ii. Design an algorithm for the given problem statement and develop a
flowchart/pseudo-code
iii. Implement the algorithm in Python language
iv. Execute the Python program
v. Test the implemented program
vi. Document the Results
vii. Analyse and discuss the outcomes of the experiment
4. Calculations/Computations/Algorithms
if num % 2 == 0:
print("Even number")
else:
print("Not even")
e. Program to print if number is even or odd using functions
def check(num):
if num % 2 == 0:
print("Even number")
else:
print("Odd number")
n = int(input("Enter a number: "))
check(n)
Name: Sakshi Tomar Roll Number: 22MPBS407016
f. function "isIn" that accepts 2 strings as arguments and returns true if either string
occurs anywhere in the other and false otherwise.
print(add(5, 10))
print(add("Hello ", "World"))
print(add([1,2], [3,4]))
h. Write a Python program to find factorial of a number using
i. User defined function without recursion
def fact_iter(n):
f=1
for i in range(1, n+1):
f *= i
return f
return n * fact_rec(n-1)
n2 = int(input("Enter a number to find factorial (recursive): "))
print("Factorial =", fact_rec(n2))
Compute the factorial of 5, 10 and 12 using both the functions and record the output.
i. Write a Python program to compute the gcd of two numbers using
i. User defined function without recursion
def gcd_iter(a, b):
while b != 0:
a, b = b, a % b
return a
5. Presentation of Results
Tomar Sakshi
d) Enter a number: 14
Even number
e) Enter a number: 9
Odd number
True
g) 15
Hello World
Name: Sakshi Tomar Roll Number: 22MPBS407016
[1, 2, 3, 4]
5! = 120
10! = 3628800
12! = 479001600
5! = 120
10! = 3628800
12! = 479001600
j) i. Iterative GCD
gcd(216, 1236) = 12
gcd(4416, 5196) = 12
gcd(216, 1236) = 12
gcd(4416, 5196) = 12
k) Reverse a String
7. Conclusions
All the programs were successfully executed using user-defined functions. The factorial and
GCD tasks proved that both iterative and recursive functions can produce correct results for
the same problem. The reverse-string program worked accurately, and the prime-number
program correctly displayed all primes below 100.
Laboratory 5
Title of the Laboratory Exercise: Data structures
3. Experimental Procedure
i. Analyse the problem statement
ii. Design an algorithm for the given problem statement and develop a
flowchart/pseudo-code
iii. Implement the algorithm in Python language
iv. Execute the Python program
v. Test the implemented program
vi. Document the Results
vii. Analyse and discuss the outcomes of the experiment
4. Calculations/Computations/Algorithms
a. Write a Python program to compute the smallest and largest elements of a list.
n = int(input("Enter number of elements: "))
lst = []
for i in range(n):
x = int(input(f"Enter element {i+1}: "))
[Link](x)
small = lst[0]
large = lst[0]
Name: Sakshi Tomar Roll Number: 22MPBS407016
cities = []
for i in range(5):
city = input(f"Enter city {i+1}: ")
[Link](city)
print("Original list:", cities)
# Insert city at 3rd position (index 2)
new_city = input("Enter a city to insert at 3rd position: ")
[Link](2, new_city)
print("List after insertion:", cities)
Name: Sakshi Tomar Roll Number: 22MPBS407016
# Using split()
words_split = [Link]()
print("Words using split():", words_split)
print("Word count (split):", len(words_split))
5. Presentation of Results
Smallest element: 27
Largest element: 69
The programs used Python lists and loops to perform different tasks such as finding
smallest/largest values, calculating sums, modifying list elements, and counting words in a
sentence. Both manual methods and built-in functions produced matching results, showing
the correctness of the logic. The experiment also showed how user input can be processed
and how list methods like append(), insert(), and pop() work.
Name: Sakshi Tomar Roll Number: 22MPBS407016
7. Conclusions
The practical helped in understanding list operations, string handling, loops, and user input in
Python. Overall, the experiment strengthened basic programming concepts and showed how
Python simplifies common data-processing tasks.
Laboratory 6
Title of the Laboratory Exercise: Data Analysis using NumPy
1. There are a number of third-party packages available for numerical and scientific computing
that extend Python’s basic math module. By far, the most commonly used packages are those
in the SciPy stack. In this lab we will focus on NumPy (Numeric Python), which provides basic
routines for manipulating large arrays and matrices of numeric data. By solving problems,
students will become familiar with the implementations mathematical and logical operations
on arrays, operations related to linear algebra, polynomials and random number generation.
3. Experimental Procedure
i. Analyse the problem statement
ii. Design an algorithm for the given problem statement and develop a
flowchart/pseudo-code
iii. Implement the algorithm in Python language
iv. Execute the Python program
v. Test the implemented program
vi. Document the Results
vii. Analyse and discuss the outcomes of the experiment
4. Calculations/Computations/Algorithms
a. Write a python program to perform the following operations and record the output.
i. Create an array containing odd numbers between 1 and 30 using built-in
function and denote it as “a”
import numpy as np
a = [Link](1, 30, 2)
print(a)
Name: Sakshi Tomar Roll Number: 22MPBS407016
v. Create an array 𝑏 = [2, 4, 6, 8, 10] and create a new array 𝑐 by joining “b” as
the fourth column of “a”.
import numpy as np
a = [Link](1, 30, 2).reshape(3, 5)
b = [Link]([2, 4, 6, 8, 10]).reshape(5, 1)
c = np.column_stack((a, b[:3]))
print(c)
vi. Make “c” as one dimensional array
import numpy as np
a = [Link](1, 30, 2).reshape(3, 5)
b = [Link]([2,4,6]).reshape(3,1)
c = np.column_stack((a, b))
c_1d = [Link]()
print(c_1d)
b. Write a Python program using built-in functions of NumPy to compute the sum,
product, maximum, minimum and the indices corresponding to maximum and
minimum of the array 𝑎 = [−1, 0.4, 7, −107, 2.3, 4.5, −51, 128, 0.01, −6,
19 ] and sort it in the decreasing order.
Name: Sakshi Tomar Roll Number: 22MPBS407016
import numpy as np
a = [Link]([-1,0.4,7,-107,2.3,4.5,-51,128,0.01,-6,19])
print("Sum =", [Link](a))
print("Product =", [Link](a))
print("Maximum =", [Link](a))
print("Minimum =", [Link](a))
print("Index of maximum =", [Link](a))
print("Index of minimum =", [Link](a))
print("Sorted decreasing =", [Link](a)[::-1])
c. Write a Python program to perform the following operations on the given array:
𝑎 = [ 11, 93, 36, 23, 6, 93, 97,92, 25, 56, 73, 117, 65, 110, 120, 67, 83, 94, 18, 20, 61,
23, 59, 52, 22, 18, 97, 31, 74, 66, 1,83, 11,65,1].
i. Create a new array “b” from array “a” which contains all odd numbers greater
than 5 and less than 100.
import numpy as np
a=[Link]([11,93,36,23,6,93,97,92,25,56,73,117,65,110,120,67,83,94,18,20
,61,23,59,52,22,18,97,31,74,66,1,83,11,65,1])
b = a[(a % 2 == 1) & (a > 5) & (a < 100)]
print("Array b:", b)
ii. Obtain the unique elements from “b”
unique_b = [Link](b)
print("Unique elements of b:", unique_b)
d. Consider the matrices:
1 1 3 12
𝐴= 1 3 4 , 𝑏= 19
−2 −2 −4 −18
Write a python program to perform the following operations.
import numpy as np
A = [Link]([[1,1,3], [1,3,4], [-2,-2,-4]])
b = [Link]([12,19,-18])
i. Compute 𝐴 ∗ 𝑏
print("A*b =", [Link](b))
ii. Compute inverse of 𝐴
print("Inverse of A:\n", [Link](A))
iii. Determine the transpose of 𝐴
print("Transpose of A:\n", A.T)
Name: Sakshi Tomar Roll Number: 22MPBS407016
e. Consider the polynomial 𝑃 (𝑥) = 𝑥 − 10𝑥 + 35𝑥 − 50𝑥 + 24. Write a python
program to perform the following operations.
i. Compute the roots of 𝑃 (𝑥)
import numpy as np
p = np.poly1d([1, -10, 35, -50, 24])
print("Roots of P4(x):", p.r)
print("Integral polynomial:", [Link]().coeffs)
print("Derivative polynomial:", [Link]().coeffs)
print("P4(6) =", p(6))
5. Presentation of Results
a. (i)[ 1 3 5 7 9 11 13 15 17 19 21 23 25 27 29]
(ii)[[ 1 3 5 7 9]
[11 13 15 17 19]
[21 23 25 27 29]]
Name: Sakshi Tomar Roll Number: 22MPBS407016
(iv) [[ 1 0 5 7 9]
[11 0 15 17 19]
[21 0 25 27 29]]
(v) [[ 1 3 5 7 9 2]
[11 13 15 17 19 4]
[21 23 25 27 29 6]]
(vi) [ 1 3 5 7 9 2 11 13 15 17 19 4 21 23 25 27 29 6]
Product = -102065440000.00002
Maximum = 128.0
Minimum = -107.0
Index of maximum = 7
Index of minimum = 3
ii)Inverse of A:
[ 1. 0. 0.5 ]]
iii)Transpose of A:
[[ 1 1 -2]
[ 1 3 -2]
[ 3 4 -4]]
iv)Determinant of A = 4.0
iii)P4(6) = 120
The programs showed how NumPy simplifies array operations, matrix calculations, and
polynomial computations. All functions worked efficiently and produced accurate outputs.
This helped understand how Python handles mathematical and scientific tasks.
7. Conclusions
All tasks were completed successfully, and the results matched expected values. The practical
improved confidence in using NumPy for arrays, matrices, and polynomial operations in
Python.
Laboratory 7
Title of the Laboratory Exercise: Plotting using Matplotlib in Python
4. Experimental Procedure
i. Analyse the problem statement
ii. Design an algorithm for the given problem statement and develop a
flowchart/pseudo-code
iii. Implement the algorithm in Python language
iv. Execute the Python program
v. Test the implemented program
vi. Document the Results
vii. Analyse and discuss the outcomes of the experiment
5. Calculations/Computations/Algorithms
a. Write a Python program to create a 2D graphs of the functions 𝑓(𝑡) = 𝑒 cos 4𝑡 and
𝑔(𝑡) = 𝑡 sin 6𝑡 + 14𝑡 − 11𝑡, 0 ≤ 𝑡 ≤ 6 in a single figure but as two subplots.
Change the colour, linewidth and line style to any value of your choice apart from the
default value. Also, insert labels, title and legend to the graph.
import numpy as np
import [Link] as plt
Name: Sakshi Tomar Roll Number: 22MPBS407016
t = [Link](0, 6, 500)
f = [Link](t) * [Link](4*t)
g = t**3 * [Link](6*t) + 14*t**2 - 11*t
[Link](figsize=(10,6))
[Link](2,1,1)
[Link](t, f, color='red', linewidth=2, linestyle='--', label='f(t)=e^t cos(4t)')
[Link]('t')
[Link]('f(t)')
[Link]('Graph of f(t)')
[Link]()
[Link](2,1,2)
[Link](t, g, color='blue', linewidth=2, linestyle='-.', label='g(t)=t^3 sin(6t)+14t^2-11t')
[Link]('t')
[Link]('g(t)')
[Link]('Graph of g(t)')
[Link]()
plt.tight_layout()
[Link]()
b. Plot a line of data ([1, 2, 3, 4], [1, 4, 9, 16]) with labelling x-axis and y-axis.
[Link](x, y, color='green')
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Line Plot")
[Link]()
Name: Sakshi Tomar Roll Number: 22MPBS407016
c. Plot a points of data ([1, 2, 3, 4], [1, 4, 9, 16]) with labelling x-axis and y-axis.
import numpy as np
import [Link] as plt
x = [Link](0, 51)
linear = x
quadratic = x**2
cubic = x**3
exponential = [Link](x/10)
[Link](x, linear, label='Linear')
[Link](x, quadratic, label='Quadratic')
[Link](x, cubic, label='Cubic')
[Link](x, exponential, label='Exponential')
[Link]("x")
[Link]("Function Values")
[Link]("Various Functions Plot")
[Link]()
[Link]()
e. Plotting data for various data types
2. Bar Plot
a. Write a Python program to create a pie chart from the given data:
b. Write a Python program to create a histogram from randomly generated 1000 data
values from a normal distribution and taking 20 bins.
import numpy as np
import [Link] as plt
data = [Link](1000)
[Link](data, bins=20, color='purple', edgecolor='black')
[Link]("Histogram of Normal Distribution (1000 Values)")
[Link]("Value")
[Link]("Frequency")
[Link]()
6. Presentation of Results
5. a
Name: Sakshi Tomar Roll Number: 22MPBS407016
b.
c.
d.
Name: Sakshi Tomar Roll Number: 22MPBS407016
e.
f.
2.a.
Name: Sakshi Tomar Roll Number: 22MPBS407016
b.
The pie chart effectively represented household expenses, and the explode feature made the
largest expense stand out clearly. The use of colors, percentages, and legend improved
readability.
The histogram of 1000 normally distributed values showed the typical bell-shaped curve,
helping visualize how data is concentrated around the mean with fewer values at the
extremes. These visualizations demonstrate how Matplotlib simplifies interpreting numerical
data.
8. Conclusions
Both the pie chart and histogram were generated successfully with clear visual interpretation.
The pie chart highlighted expense distribution, and the histogram illustrated random data
behavior.
This experiment strengthened the understanding of presenting data graphically and using
Python's Matplotlib for effective data visualization.
Laboratory 8
Title of the Laboratory Exercise: Introduction to Predictive Artificial Intelligence
9. Experimental Procedure
i. Analyse the problem statement
ii. Design an algorithm for the given problem statement and develop a
flowchart/pseudo-code
iii. Implement the algorithm in Python language
iv. Execute the Python program
v. Test the implemented program
vi. Document the Results
vii. Analyse and discuss the outcomes of the experiment
10. Calculations/Computations/Algorithms
i. Implementation of perceptron in Python
Name: Sakshi Tomar Roll Number: 22MPBS407016
Name: Sakshi Tomar Roll Number: 22MPBS407016
Name: Sakshi Tomar Roll Number: 22MPBS407016
Using this perceptron implementation, we can now initialize new Perceptron objects with a given
learning rate 𝜂 and the number of epochs n_iter (passes over the training dataset)
Via the fit method, we can initialize the bias self.b_ to an initial value 0 and the weights in self.w_ to a
vector, R^m , where m stands for the number of dimensions in the data set.