0% found this document useful (0 votes)
7 views48 pages

Python Lab Exercises for B.Sc. Students

Uploaded by

thecosmosblogs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views48 pages

Python Lab Exercises for B.Sc. Students

Uploaded by

thecosmosblogs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Name: Sakshi Tomar Roll Number: 22MPBS407016

PYM412A: Python and Laboratory


[Link]. (Hons)

7th Semester

Name Sakshi Tomar


University Id 22MPBS407016

Faculty of Natural Sciences


Ramaiah University of Applied Sciences
Name: Sakshi Tomar Ramaiah University of Applied
Roll Sciences
Number: 22MPBS407016
Private University Established in Karnataka State by Act No. 15 of 2013

Faculty Natural Sciences

Programme [Link]. (Hons) in Physics

Year/Semester 4/7

Name of the Laboratory Python and Laboratory

Course Code PYM412A

List of laboratory exercises:

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

Viva Results Documentation Total


No. Lab Experiment Marks
(8) (12) (5) (25)

Introduction to Python
1

Variables and operations in Python


2

Control structures and loops in Python


3

Functions in Python
4

Data Structures in Python


5

Data analysis using NumPy in Python


6

Plots using Matplotlib in Python


7

10

Total Marks out of 25

Component 1 (Lab Internal Marks) = Signature of the Staff In-charge


Name: Sakshi Tomar Roll Number: 22MPBS407016

Laboratory 1
Title of the Laboratory Exercise: Introduction to Python

1. Introduction and Purpose of Experiment


Python is a high level, interactive, interpreted, object oriented scripting language. In this
laboratory exercise, students get familiar with the program development using a text editor
and run Python programs in powershell using a set of simple exercises.

2. Aim and Objectives


Aim
 To familiarise Jupyter, interpreter and simple Python programs
Objectives
At the end of this lab, the student will be able to
 Explain the Python features
 Write and execute simple Python programs

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

 Print the following statements in exactly the way they appear


i. hello,world!
HI from india
print("hello, world!\nHi from india")
ii. I am running python for the first time

print("I am \t running python\t\tfor the first\t\ttime")

 Evaluate the following


i. 3 , (−2) , 153 , (−5)
print("3^6 =", 3**6)
print("(-2)^5 =", (-2)**5)
print("153^(-2) =", 153**(-2))
Name: Sakshi Tomar Roll Number: 22MPBS407016

print("(-5)^(-4) =", (-5)**(-4), "\n")


ii. Compute the remainder and dividend when 92739232973 is divided by 17 and
123231321321 is divided by 11.
s = 92739232973
t = 17
print("quotient =", s//t, ", remainder =", s % t)
e = 123231321321
f = 11
print("quotient =", e//f, ", remainder =", e% f,)
iii. Absolute value of 3 + 4𝑖, 43 − 22𝑖
z1 = 3 + 4j
z2 = 43 – 22j
print("|3 + 4i| =", abs(z1))
print("|43 - 22i| =", abs(z2))
iv. Getting the class of any number
n = eval(input("Enter any number: "))
print("The class of the given number is:", type(n))
v. Converting int to float and vice versa,
n = int(input("Enter an integer: "))
print("As float =", float(n))

x = float(input("Enter a float number: "))


print("As int =", int(x))

vi. Factorial of first five odd number bigger than five.


import math
for n in [7,9,11,13,15]:
print(f"{n}! = {[Link](n)}")
vii. sin , cos 𝜋 , tan , sec 1 , 𝑒 , log(19).

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

print("log(19) =", [Link](19))

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

v) Trigonometric, Exponential, and Logarithmic Values


sin (𝜋/6) = 0.5
cos (𝜋) = −1
tan (𝜋/2)approaches infinity, Python shows a very large value.

sec (1) = ( )
≈ 1.8508

𝑒 ≈ 20.085
ln (19) ≈ 2.944

6. Analysis and Discussions


In this experiment, Python was used to carry out different mathematical operations such as
exponent calculations, division with remainder, absolute values of complex numbers,
factorials, and evaluation of trigonometric and logarithmic functions.
7. Conclusions This practical showed that Python is a reliable and easy tool for doing
mathematical computations.

Signature of Staff in-charge


Name: Sakshi Tomar Roll Number: 22MPBS407016

Laboratory 2
Title of the Laboratory Exercise: Variables, operators and expressions

1. Introduction and Purpose of Experiment


Variables are the basic data objects that are manipulated in a program. Operators specify what
is to be done to them. Expressions combine variables and constants to produce new values.
These building blocks are the topics of this Lab. By solving the given programming problems,
the students will be able to apply the concepts of variables, operators and expressions.

2. Aim and Objectives

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

a. Write a program to swap two numbers


i. Using temporary variable
a = 10
b = 20
temp = a
a=b
b = temp
print("After swapping (using temp):", a, b)
ii. Without using temporary variable
a = 10
b = 20
print("Before swapping:", a, b)
a=a+b
b=a-b
a=a-b
print("After swapping (without temp):", a, b)
b. Write a program to calculate and printing time after taking distance and rate as inputs
from the user
distance = float(input("Enter distance: "))
rate = float(input("Enter rate (speed): "))
time = distance / rate
print("Time =", time)
c. Write a program to find the area and circumference of a circle/perimeter and area of a
rectangle
import math
# Circle
r = float(input("Enter radius of the circle: "))
area_circle = [Link] * r * r
circumference = 2 * [Link] * r

print("Area of circle =", area_circle)


print("Circumference of circle =", circumference)
Name: Sakshi Tomar Roll Number: 22MPBS407016

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

print("Area of rectangle =", area_rect)


print("Perimeter of rectangle =", perimeter_rect)
d. Program to demonstrate len function
text = input("Enter any text: ")
print("Length of the text =", len(text))

5. Presentation of Results

4a. Swapping Two Numbers

i) After swapping (using temp): 20 10

ii) Before swapping: 10 20

After swapping (without temp): 20 10

b. Enter distance: 150

Enter rate (speed): 50

Time = 3.0

c. Enter radius of the circle: 7

Area of circle = 153.93804002589985

Circumference of circle = 43.982297150257104

Enter length of the rectangle: 10

Enter width of the rectangle: 5

Area of rectangle = 50

Perimeter of rectangle = 30
Name: Sakshi Tomar Roll Number: 22MPBS407016

d. Enter any text: Hello Python

Length of the text = 12

6. Analysis and Discussions

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

Signature of Staff in-charge


Name: Sakshi Tomar Roll Number: 22MPBS407016

Laboratory 3
Title of the Laboratory Exercise: Control structures in Python

1. Introduction and Purpose of Experiment


Python provides number of control flow instructions/statements to control the flow of
program execution conditionally. By solving the problems, students will be able to apply
conditional control statements to control the program execution.
Loop statements are used to repeat a statement or set of statements multiple times. By
solving the problems students will be able to apply iterative control statements to control the
program execution.

2. Aim and Objectives


Aim
 To develop programs involving loops and branching using appropriate Python
language control statements
Objectives
At the end of this lab, the student will be able to
 Apply control statements such as if-else, nested if-else to express decisions
 Use the switch statement to create multiple branching based on expression matching
 Create C programs using loops such as for, while, do-while to repeat a block of code

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

b = int(input("Enter second number: "))


c = int(input("Enter third number: "))
if a > b and a > c:
greatest = a
elif b > c:
greatest = b
else:
greatest = c
print("Greatest number is:", greatest)

b. Program to interchange the values stored in two variables say x and y


x = input("Enter value of x: ")
y = input("Enter value of y: ")

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

d. Program to demonstrate * and + operations on strings


s1 = "Hello"
s2 = "Python"

print("Using + :", s1 + " " + s2)


print("Using * :", s1 * 3)
e. Program to save a secret number and checking if the input matches with the number
secret = 45
guess = int(input("Enter your guess: "))

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

if [Link]() == "yes" and baggage <= 20:


print("Passenger is allowed to board.")
else:
print("Passenger is NOT allowed to board.")
g. Programs to demonstrate if else, if elif else statements
i)
age = int(input("Enter age: "))
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
ii)
marks = int(input("Enter marks: "))
if marks >= 75:
print("Grade A")
elif marks >= 60:
Name: Sakshi Tomar Roll Number: 22MPBS407016

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

a) Greatest of Three Numbers

Enter first number: 12


Enter second number: 45
Enter third number: 9

Greatest number is: 45

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

d) Using + : Hello Python

Using * : HelloHelloHello

e) Enter your guess: 45


Correct! You've guessed the secret number.
f) Do you have a valid ticket? (yes/no): yes
Enter baggage weight in kg: 18
Passenger is allowed to board.
g) i) Enter age: 16
You are not eligible to vote.
ii) Enter marks: 72
Grade B
h) Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
i) Enter a number: 5
0
1
2
3
4
5
j) i. Enter a number: 5
Factorial = 120
ii) Enter a number: 6
Factorial = 720
k) 1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
Name: Sakshi Tomar Roll Number: 22MPBS407016

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

Integer square root: 7

6. Analysis and Discussions

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.

Signature of Staff in-charge


Name: Sakshi Tomar Roll Number: 22MPBS407016

Laboratory 4
Title of the Laboratory Exercise: Functions

1. Introduction and Purpose of Experiment


A function serves as an abstraction mechanism to view many things as one thing. The function
definition specifies the name of a new function and the sequence of statements that execute
when the function is called. Once a function is defined, it can be called as many times as
required. By solving these problems, students will be able to create user defined functions.

2. Aim and Objectives


Aim
 To develop programs using user defined functions
Objectives
At the end of this lab, the student will be able to
 Apply user defined functions with proper definition

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. Program to print any text using function


def show_text():
print("Hello, this is a function printing text!")
show_text()
b. Program to print largest of two numbers using formal parameter in functions
def largest(x, y):
if x > y:
Name: Sakshi Tomar Roll Number: 22MPBS407016

print("Largest number is:", x)


else:
print("Largest number is:", y)
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
largest(a, b)
c. Program to print first name and last name in the same order or reverse order using
functions
def print_names(fname, lname, order):
if order == 1:
print(fname, lname)
else:
print(lname, fname)

fname = input("Enter first name: ")


lname = input("Enter last name: ")
choice = int(input("Enter 1 for normal order or 2 for reverse order: "))

print_names(fname, lname, choice)


d. Program to print if entered number is even
num = int(input("Enter a number: "))

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.

def isIn(a, b):


if a in b or b in a:
return True
else:
return False
s1 = input("Enter first string: ")
s2 = input("Enter second string: ")
print(isIn(s1, s2))

g. Program to demonstrate polymorphism in functions


def add(a, b):
return a + b

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

n1 = int(input("Enter a number to find factorial (iterative): "))


print("Factorial =", fact_iter(n1))

ii. User defined recursive function


def fact_rec(n):
if n == 0 or n == 1:
return 1
else:
Name: Sakshi Tomar Roll Number: 22MPBS407016

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

x = int(input("Enter first number: "))


y = int(input("Enter second number: "))

print("GCD (iterative) =", gcd_iter(x, y))


ii. User defined recursive function
def gcd_rec(a, b):
if b == 0:
return a
else:
return gcd_rec(b, a % b)
x1 = int(input("Enter first number: "))
y1 = int(input("Enter second number: "))
print("GCD (recursive) =", gcd_rec(x1, y1))

j. Write a Python function to reverse a string.


def reverse_string(s):
return s[::-1]
text = input("Enter a string to reverse: ")
print("Reversed string:", reverse_string(text))
k. Write a Python function to check whether the given number is prime or not. Using
this function, display all prime numbers below 100.
def is_prime(n):
if n <= 1:
return False
Name: Sakshi Tomar Roll Number: 22MPBS407016

for i in range(2, int(n**0.5) + 1):


if n % i == 0:
return False
return True

# Display all prime numbers below 100


print("Prime numbers below 100 are:")
for num in range(2, 100):
if is_prime(num):
print(num, end=" ")

5. Presentation of Results

a) Hello, this is a function printing text!

b) Enter first number: 12


Enter second number: 25

Largest number is: 25

c) Enter first name: Sakshi

Enter last name: Tomar

Enter 1 for normal order or 2 for reverse order: 2

Tomar Sakshi

d) Enter a number: 14
Even number
e) Enter a number: 9
Odd number

f) Enter first string: rain

Enter second string: rainbow

True

g) 15

Hello World
Name: Sakshi Tomar Roll Number: 22MPBS407016

[1, 2, 3, 4]

h)i Iterative Factorial

Enter a number to find factorial (iterative): 5

Enter a number to find factorial (iterative): 10

Enter a number to find factorial (iterative): 12

5! = 120

10! = 3628800

12! = 479001600

ii) Recursive Factorial

Enter a number to find factorial (recursive): 5

Enter a number to find factorial (recursive): 10

Enter a number to find factorial (recursive): 12

5! = 120

10! = 3628800

12! = 479001600

j) i. Iterative GCD

Enter first number: 216

Enter second number: 1236

Enter first number: 4416

Enter second number: 5196

gcd(216, 1236) = 12

gcd(4416, 5196) = 12

ii) Recursive GCD

Enter first number: 216

Enter second number: 1236


Name: Sakshi Tomar Roll Number: 22MPBS407016

Enter first number: 4416

Enter second number: 5196

gcd(216, 1236) = 12

gcd(4416, 5196) = 12

k) Reverse a String

Enter a string to reverse: laboratory

Reversed string: yrotarobal

l)Prime Check + All Primes Below 100

Prime numbers are: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79


83 89 97

6. Analysis and Discussions

In this experiment, Python user-defined functions were used to perform different


computational tasks such as factorial calculation, finding GCD, reversing strings, and checking
prime numbers. Both iterative and recursive approaches for factorials and GCD showed the
same correct results, which helped in understanding how recursion works internally
compared to loops.

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.

Signature of Staff in-charge


Name: Sakshi Tomar Roll Number: 22MPBS407016

Laboratory 5
Title of the Laboratory Exercise: Data structures

1. Introduction and Purpose of Experiment


Data structure is a way of collecting and organizing data in such a way that various operations
can be done on these data in an effective way. By solving these problems, students will
become familiar with the implementations of strings, lists, tuples and sets.

2. Aim and Objectives


Aim
 To develop programs based on data structures
Objectives
At the end of this lab, the student will be able to
 Use of appropriate data structure to store data
 Create Python programs of basic data structures such as strings, lists, tuples and sets.

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

for num in lst[1:]:


if num < small:
small = num
if num > large:
large = num
print("Smallest element:", small)
print("Largest element:", large)
b. Write a Python program to compute the sum of all the elements of a given list
i. Using index
lst = [-31, 125, 77, -24, -342, 623, 9]
sum_index = 0
for i in range(len(lst)):
sum_index += lst[i]
print("Sum using index =", sum_index)
ii. Without using index
lst = [-31, 125, 77, -24, -342, 623, 9]
sum_no_index = 0
for x in lst:
sum_no_index += x
print("Sum without index =", sum_no_index)
Using your program, compute the sum of elements of [-31, 125, 77, -24, -342, 623, 9].
c. Write a python program to create a list of five cities of Karnataka, using built-in python
functions input() and append(). Insert one more name of the city in the 3th position
and remove the 2th element of list. Display your list in each step.

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

# Remove the 2nd element (index 1)


removed = [Link](1)
print("List after removing 2nd element:", cities)
d. Write a python program to count the number of words and print all the words in a
given sentence. Compare your results with the built-in split() method.

sentence = input("Enter a sentence: ")


words_manual = []
word = ""
for ch in sentence:
if ch == " ":
if word != "":
words_manual.append(word)
word = ""
else:
word += ch
if word != "":
words_manual.append(word)
print("Words using manual method:", words_manual)
print("Word count (manual):", len(words_manual))

# Using split()
words_split = [Link]()
print("Words using split():", words_split)
print("Word count (split):", len(words_split))

5. Presentation of Results

(a) Smallest & Largest Element of a List

Enter number of elements: 5


Enter element 1: 69
Enter element 2: 32
Enter element 3: 46
Enter element 4: 65
Enter element 5: 27
Name: Sakshi Tomar Roll Number: 22MPBS407016

Smallest element: 27
Largest element: 69

(b) Sum of List Elements (Index & Without Index)

Sum using index = 437


Sum without index = 437

(c) List of Five Karnataka Cities (Insert + Remove)

Enter city 1: Bengaluru


Enter city 2: Mysuru
Enter city 3: Mangalore
Enter city 4: Hubli
Enter city 5: Belagavi

List after insertion:['Bengaluru', 'Mysuru', 'Tumkur', 'Mangalore', 'Hubli', 'Belagavi']


List after removing 2nd element: ['Bengaluru', 'Tumkur', 'Mangalore', 'Hubli',
'Belagavi']
(d) Counting Words & Comparing With split()
Enter a sentence: hello from python 22mpbs407016
Words using manual method: ['hello', 'from', 'python', '22mpbs407016']
Word count (manual): 4
Words using split(): ['hello', 'from', 'python', '22mpbs407016']
Word count (split): 4

6. Analysis and Discussions

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.

Signature of Staff in-charge


Name: Sakshi Tomar Roll Number: 22MPBS407016

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.

2. Aim and Objectives


Aim
 To learn basic operations NumPy and develop programs based it.
Objectives
At the end of this lab, the student will be able to
 Perform Mathematical and logical operations on arrays.
 Use built-in functions of NumPy to manipulate data.

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

ii. Change the shape of “a” to 3 × 5.


import numpy as np
a = [Link](1, 30, 2)
a = [Link](3, 5)
print(a)
iii. Extract 3rd row of “a” and 2nd column of “a”
third_row = a[2, :]
second_column = a[:, 1]

print("3rd row:", third_row)


print("2nd column:", second_column)
iv. Set the values of 2nd column of “a” to contain only zeros.
a[:, 1] = 0
print(a)

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

iv. Compute the determinant of 𝐴


print("Determinant of A =", [Link](A))
v. Extract the diagonal elements of 𝐴
print("Diagonal elements =", [Link](A))
vi. Solve the system of linear equations 𝐴𝑋 = 𝑏, where 𝑋 = [𝑥, 𝑦, 𝑧] .
X = [Link](A, b)
print("Solution of AX=b:", X)

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

ii. Compute the polynomials obtained by integration and differentiation of 𝑃 (𝑥).

print("Integral polynomial:", [Link]().coeffs)


print("Derivative polynomial:", [Link]().coeffs)

iii. Evaluate 𝑃 (𝑥) at 𝑥 = 6.


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

(iii) 3rd row: [21 23 25 27 29]


2nd column: [ 3 13 23]

(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]

(b) Sum = -3.79

Product = -102065440000.00002

Maximum = 128.0

Minimum = -107.0

Index of maximum = 7

Index of minimum = 3

Sorted decreasing = [ 1.2800e+02 1.9000e+01 7.0000e+00 4.5000e+00 2.3000e+00


4.0000e-01 1.0000e-02 -1.0000e+00 -6.0000e+00 -5.1000e+01 -1.0700e+02]

(c) i) Array b: [11 93 23 93 97 25 73 65 67 83 61 23 59 97 31 83 11 65]

ii) Unique elements of b: [11 23 25 31 59 61 65 67 73 83 93 97]

(d) i) A*b = [-23 -3 10]

ii)Inverse of A:

[[-1. -0.5 -1.25]

[-1. 0.5 -0.25]

[ 1. 0. 0.5 ]]

iii)Transpose of A:

[[ 1 1 -2]

[ 1 3 -2]

[ 3 4 -4]]

iv)Determinant of A = 4.0

v)Diagonal elements = [ 1 3 -4]

vi)Solution of AX=b: [1. 2. 3.]


Name: Sakshi Tomar Roll Number: 22MPBS407016

(e)i) Roots of P4(x): [4. 3. 2. 1.]

ii)Integral polynomial: [ 0.2 -2.5 11.66666667 -25. 24. 0 ]

Derivative polynomial: [ 4 -30 70 -50]

iii)P4(6) = 120

6. Analysis and Discussions

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.

Signature of Staff in-charge


Name: Sakshi Tomar Roll Number: 22MPBS407016

Laboratory 7
Title of the Laboratory Exercise: Plotting using Matplotlib in Python

1. Introduction and Purpose of Experiment


2. Matplotlib is a Python 2D plotting library which produces publication quality figures in a
variety of hardcopy formats and interactive environments across platforms. Matplotlib can be
used in Python scripts, the Python and Ipython shells, the Jupyter notebook, web application
servers, and four graphical user interface toolkits. Matplotlib tries to make easy things easy
and hard things possible. You can generate plots, histograms, power spectra, bar charts, error
charts, scatterplots, etc., with just a few lines of code.

3. Aim and Objectives


Aim
 To develop programs using Matplotlib library of Python.
Objectives
At the end of this lab, the student will be able to
 Use built-in library functions of the module pyplot
 Create 2D graphs of different types of data 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.

import [Link] as plt


x = [1, 2, 3, 4]
y = [1, 4, 9, 16]

[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 [Link] as plt


x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
[Link](x, y, color='purple')
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Scatter Plot")
[Link]()
d. Write a program to create a list containing number from 0 to 50 and calculate linear,
quadratic, cubic and exponential functions of these number and plot of a graph of
these in a single plot. Also label the axes and plots along with legends.

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

import [Link] as plt


numbers = [1, 2, 3, 4, 5]
strings = ['A', 'B', 'C', 'D', 'E']
Name: Sakshi Tomar Roll Number: 22MPBS407016

[Link](numbers, numbers, label='Numbers')


[Link](numbers, [x*2 for x in numbers], label='Twice Values')
[Link]("Index")
[Link]("Values")
[Link]("Plot for Various Data Types")
[Link]()
[Link]()
f. Plot scatter data randomly generated.
import numpy as np
import [Link] as plt
x = [Link](100)
y = [Link](100)
[Link](x, y, color='red')
[Link]("Random Scatter Plot")
[Link]("X")
[Link]("Y")
[Link]()

2. Bar Plot

a. Write a Python program to create a pie chart from the given data:

Monthly household expenses


House Rent 12000
Utilities 3000
Food 5000
Entertainment 3000
Travel 3000
Make the largest expense standout from others and display title, legend, shadow
effect and percentage of expenses. Choose different colours and radius as 2 units.

import [Link] as plt


labels = ['House Rent', 'Utilities', 'Food', 'Entertainment', 'Travel']
expenses = [12000, 3000, 5000, 3000, 3000]
colors = ['red', 'yellow', 'lightblue', 'green', 'orange']
explode = [0.2, 0, 0, 0, 0]
Name: Sakshi Tomar Roll Number: 22MPBS407016

[Link](expenses, labels=labels, colors=colors, explode=explode,


autopct='%1.1f%%', shadow=True, radius=2)
[Link]("Monthly Household Expenses")
[Link](labels)
[Link]()

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.

7. Analysis and Discussions

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.

Signature of Staff in-charge


Name: Sakshi Tomar Roll Number: 22MPBS407016

Laboratory 8
Title of the Laboratory Exercise: Introduction to Predictive Artificial Intelligence

Introduction and Purpose of Experiment


Artificial intelligence (AI) involving self-learning algorithms that derive knowledge from data
to make predictions.
Aim and Objectives
Aim
 To develop simple programs in PyTorch/TensorFlow to understand fundamental of
supervised learning.
Objectives
At the end of this lab, the student will be able to
 Train simple machine learning algorithms for classification

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

11. Analysis and Discussions

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.

Signature of Staff in-charge

You might also like