Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
29 views

Lab Manual_Python Programming

The document is a lab manual for the Python Programming course at A.C. Patil College of Engineering, detailing lab outcomes, program outcomes, and a list of experiments for students. It outlines the skills students will acquire, including proficiency in Python programming, data structures, file operations, and GUI design. Additionally, it includes specific experiment aims and requirements for practical coding exercises to enhance learning in Python.

Uploaded by

shreyash12440
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Lab Manual_Python Programming

The document is a lab manual for the Python Programming course at A.C. Patil College of Engineering, detailing lab outcomes, program outcomes, and a list of experiments for students. It outlines the skills students will acquire, including proficiency in Python programming, data structures, file operations, and GUI design. Additionally, it includes specific experiment aims and requirements for practical coding exercises to enhance learning in Python.

Uploaded by

shreyash12440
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 78

Jawahar Education Society’s

A.C.Patil College of Engineering,Kharghar,Navi Mumbai.


Department of Humanity and Science
Sem-II Even Sem Year 2024-25

Lab Manual

Course Name-Python Programming


Course Code-VSEC202

Prepared by –Prof.P.T.Yewale

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 1


Jawahar Education Society’s
A.C.Patil College of Engineering,Kharghar,Navi Mumbai.
Department of humanity and science
Sem-II Even Sem Year 2024-25

Course Name-Python Programming


Course Code-VSEC202

Lab Outcomes

Lab Outcomes: Learner will be able to

LO. LO Cognitive
Number. level
1 Demonstrate the proficiency in basic python programming or Apply
Create and perform various operations on data structures like list,
tuple dictionaries and strings.
2 Apply Control Flow and Functions for efficient coding to solve Apply
problems.
3 Demonstrate proficiency in handling file operations, managing Apply
exceptions, and developing Python packages and executable files
for modular programming.
4 Illustrate the concept of Object-Oriented Programming used in Apply
python.
5 Design Graphical User Interface (GUI) applications, utilizing Create
appropriate Python libraries to create user-friendly interfaces.
6 Investigate and apply popular python libraries to conduct efficient Create
data handling tasks.

Prof.Pandit T.Yewale Dr.M.S.Selokar


Subject teacher Head of Department

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 2


Jawahar Education Society’s
A.C.Patil College of Engineering,Kharghar,Navi Mumbai.
Department of humanity and science

Program outcomes (POs)- Engineering & Technology

Engineering Graduates will be able to:

PO1.- Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.

PO2.- Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.

PO3.- Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.

PO4.- Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.

PO5.- Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex engineering
activities with an understanding of the limitations.

PO6.- The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.

PO7.- Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 3


PO8.- Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.

PO9.- Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.

PO10.- Communication: Communicate effectively on complex engineering activities with the


engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.

PO11.- Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.

PO12.- Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological change.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 4


Jawahar Education Society’s
A.C.Patil College of Engineering,Kharghar,Navi Mumbai.
Department of humanity and science
Sem-II Even Sem Year 2024-25

Course Name-Python Programming


Course Code-VSEC202

LO-PO Matrix-

LO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
1 3 3 2 1 3 1 3 2 1 1
2 3 3 2 1 3 1 3 2 1 1
3 3 3 2 1 3 1 3 2 1 1
4 3 3 2 1 3 1 3 2 1 1
5 3 3 2 1 3 1 3 2 1 1
6 3 3 2 1 3 1 3 2 1 1

LO-PSO Matrix-

LO PSO1 PSO2
1 - -
2 - -
3 - -
4 - -
5 - -
6 - -

Prof.Pandit T.Yewale Dr.M.S.Selokar


Subject teacher Head of Department

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 5


Jawahar Education Society’s
A.C.Patil College of Engineering,Kharghar,Navi Mumbai.
Department of humanity and science
Sem-II Even Sem Year 2024-25

Course Name-Python Programming


Course Code-VSEC202
List of Experiments.
Expt Experiment name LO PO
no
1 Aim-Write a python code to generate Personalized Greeting.
2 Aim-Write a python program to calculate areas of any
geometric figures like circle, rectangle and triangle.
3 Aim- Write a Python program to calculate the gross salary of
an employee. The program should prompt the user for the basic
salary (BS) and then compute the dearness allowance (DA) as
70% of BS, the travel allowance (TA) as 30% of BS, and the
house rent allowance (HRA) as 10% of BS. Finally, it should
calculate the gross salary as the sum of BS, DA, TA, and HRA
and display the result.
4 Aim-Write a Python program to explore basic arithmetic
operations. The program should prompt the user to enter two
numbers and then perform addition, subtraction, multiplication,
division, and modulus operations on those numbers. The results
of each operation should be displayed to the user.
5 Aim- Develop a Python program to manage a task list using
lists and tuples, including adding, removing, updating, and
sorting tasks.
6 Aim-Create a Python code to demonstrate the use of sets and perform
set operations (union, intersection, difference) to manage student
enrollments in multiple courses / appearing for multiple entrance
exams like CET, JEE, NEET etc.

7 Aim-Write a Python program to create, update, and manipulate a


dictionary of student records, including their grades and attendance
8 Aim-Develop a Python program that takes a numerical input and
identifies whether it is even or odd, utilizing conditional statements
and loops.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 6


9 Aim-Design a Python program to compute the factorial of a given
integer N.

10 Aim-Using function, write a Python program to analyze the input


number is prime or not.

11 Aim-Implement a simple Python calculator that takes user input and


performs basic arithmetic operations (addition, subtraction,
multiplication, division) using functions.

12 Aim-Develop a Python program that reads a text file and prints words
of specified lengths (e.g., three, four, five, etc.) found within the file.

13 Aim-Create a executable file for any program developed in earlier


practical.

14 Aim-Write a Python program that takes two numbers as input and


performs division. Implement exception handling to manage division
by zero and invalid input errors gracefully.

15 Aim-Demonstrate the use of a Python debugger (e.g., pdb or an IDE


with debugging capabilities) on a sample program with intentional
errors. Guide students on setting breakpoints, stepping through code,
and examining variable values.

16 Aim-Develop classes for products, customers, and shopping carts.


Include methods for adding items to the cart, calculating total costs,
processing orders, and managing inventory.

17 Aim-The college admission registration form collects essential


personal, educational, and contact information from prospective
students. Create a GUI as shown in Figure-1 that allows the user to
input his/her name, branch and favorite game. When the user clicks
the Submit button, it should display the output as illustrated.

18 Aim- Write a Python script that prompts the user to enter their phone
number and email ID. It then employs Regular Expressions to verify
if these inputs adhere to standard phone number and email address
formats

19 Aim- Create a program that reads a text file containing various


data (e.g., names, emails, phone numbers). Use regular
expressions to extract specific types of data, such as email
addresses, phone numbers, dates (e.g., MM/DD/YYYY
format).

20 Aim-Write a Python program to create a 1D, 2D, and 3D NumPy


array. Perform basic operations like reshaping, slicing, and indexing.

21 Aim-Develop a Python script to create two arrays of the same shape

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 7


and perform element-wise addition, subtraction, multiplication, and
division. Calculate the dot product and cross product of two vectors.

22 Aim-Write a Python program to calculate mean, median, standard


deviation, variance, and correlation coefficients of a given array.

23

Prof.Pandit T.Yewale Dr.M.S.Selokar


Subject teacher Head of Department

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 8


Objective:
To enable learners to transition their
understanding of basic programming
constructs from C to Python by focusing on
Python's syntax, variables, data types,
operators, and input/output functions, and
comparing these elements with their
equivalents in C

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 9


Experiment no 1

Personalized Greeting Generator* -

Aim-Write a python code to generate Personalized Greeting.

Requirement: Python 3.13.1

Theory-
Name and greet" is a simple Python project that allows the user to input their name
and select a type of greeting. Based on their choice, the program outputs a
personalized greeting. This project is a great way to get started with Python
programming and practicing input/output functionality, if/else statements, and user
prompts.

The program can be customized and expanded by adding more greeting options or
by making the program more interactive, such as asking the user additional
questions or providing them with more choices. With a few modifications, this
project can be turned into a more complex chatbot or an interactive user interface
for greeting people.

 Open your Python development environment (such as IDLE or PyCharm).

 Create a new Python file and name it as greeting.py.

 Start by printing a welcome message to the user:


python

print("Welcome to the name and greet program!")

 Next, prompt the user to enter their name:

name = input("Please enter your name: ")

 Once the user enters their name, prompt them to select a type of greeting:

print(f"Hi {name}! How would you like to be greeted?")


print("1. Say hello")
print("2. Wave")

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 10


print("3. Smile")

choice = input("Enter your choice (1/2/3): ")

 Now, based on the user's choice, output a personalized greeting:

if choice == "1":
print(f"Hello {name}, wishing you a pleasant day from here")

elif choice == "2":


print(f"Nice to meet you {name}! Waves")

elif choice == "3":


print(f"It's so nice to meet you with a smile {name}. The Lord is your
strength")

else:
print("Invalid choice. Please enter 1, 2 or 3.")

 Finally, print a thank you message to the user:

print("Thanks for using the name and greet program!")

 Save the file and run the program to test it out.


python3 greeting.py

That's it! This simple program prompts the user to enter their name and then allows
them to select a type of greeting. Based on their choice, a personalized greeting is
displayed.

Program Code-

# Python program that asks the user to enter their name, and then greet them.

print("Welcome to the name and greet program!")


name = input("Please enter your name: ")
print("Hi {name}! How would you like to be greeted?")
print("1. Say hello")
print("2. Wave")
print("3. Smile")
choice = input("Enter your choice (1/2/3): ")

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 11


if choice == "1":
print(f"Hello {name}, wishing you a pleasant day from here")
elif choice == "2":
print(f"Nice to meet you {name}! Waves")
elif choice == "3":
print(f"It's so nice to meet you with a smile {name}. The Lord is your strength")
else:
print("Invalid choice. Please enter 1, 2 or 3.")

print("Thanks for using the name and greet program!")

Output of Program:-

Welcome to the name and greet program!


Please enter your name: pandit
Hi pandit! How would you like to be greeted?
1. Say hello
2. Wave
3. Smile
Enter your choice (1/2/3): 3
It's so nice to meet you with a smile pandit. The Lord is your strength
Thanks for using the name and greet program!

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 12


Experiment no 2

Calculating Areas of Geometric Figures* -

Aim-Write a python program to calculate areas of any geometric figures like


circle, rectangle and triangle.

Requirement: Python 3.13.1

Theory-

In this program we will calculate the area of different geometrical shapes based on
the user's choice and input. We will have five geometrical shapes: circle, rectangle,
triangle, square, and parallelogram. Users can choose the shape and provide the
required input fields to calculate its area.

We will use the following formulas to calculate the area of the circle, rectangle,
triangle, square, and parallelogram:

 Area of circle = 3.1459* radius*radius

The logic to calculate the area of the circle will be

area = (float)3.14159*radius*radius;

 Area of the rectangle = length* breadth

The logic to calculate the area of the circle will be

area = (float)length*breadth;

 Area of a triangle (with three sides given a, b, and c) = Square root


of [s(s-a)(s-b)(s-c)] , where s = (a+b+c)/2

The logic to calculate the area of the circle will be

s = (float)(a+b+c)/2;

area = (float)(sqrt(s*(s-a)*(s-b)*(s-c)));

 Area of a square = side*side

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 13


The logic to calculate the area of the circle will be

area = (float)side*side;

 Area of Parallelogram = base*height

The logic to calculate the area of the circle will be:

area = (float)base*height;

We have used a switch case in all programs and calculated the area of a shape
depending on the input provided by users.

Program Code-

# Area Calculator in Python

import math

print("**********Choose an Option:********* ");

print("1: Area of the Circle");

print("2: Area of the Rectangle ");

print("3: Area of the Triangle ");

print("4: Area of the Square ");

print("5: Area of the Parallelogram ");

# input the desired shape

choice = int(input(""))

# area of a circle

if choice==1:

# input circle radius

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 14


radius = float(input("Enter the radius of the Circle: "))

area = math.pi*pow(radius,2)

print(f"The area of the circle with radius {radius} is : {round(area,2)}")

#area of a rectangle

elif choice==2:

width =float(input("Enter the width of the rectangle: "))

length = float(input("Enter the length of the rectangle: "))

area = width*length

print(f"The area of the rectangle is {round(area,2)}")

# area of a triangle using Heron's formula

elif choice ==3:

a, b , c = map(float, input("Enter the 3 sides of triangle eg (12 13 14):").split())

s= (a+b+c)/2

area = math.sqrt(s*(s-a)*(s-b)*(s-c))

print(f"The area of the triangle is {round(area,2)}")

#area of a Square

elif choice ==4:

side =float(input("Enter the side of the square: "))

area = side*side

print(f"The area of the square is {round(area,2)}")

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 15


#area of a Parallelogram

elif choice ==5:

base =float(input("Enter the base of the parallelogram: "))

height = float(input("Enter the height of the parallelogram: "))

area = base*height

print(f"The area of the parallelogram is {round(area,2)}")

else:

print("Wrong Choice")

Output of Program:-

**********Choose an Option:*********
1: Area of the Circle
2: Area of the Rectangle
3: Area of the Triangle
4: Area of the Square
5: Area of the Parallelogram
1
Enter the radius of the Circle: 4
The area of the circle with radius 4.0 is : 50.27

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 16


Experiment no 3

Calculating Gross Salary of an Employee*:

Aim- Write a Python program to calculate the gross salary of an employee. The
program should prompt the user for the basic salary (BS) and then compute the
dearness allowance (DA) as 70% of BS, the travel allowance (TA) as 30% of BS,
and the house rent allowance (HRA) as 10% of BS. Finally, it should calculate the
gross salary as the sum of BS, DA, TA, and HRA and display the result.

Requirement: Python 3.13.1

Program Code-

# Python3 program to implement the above approach

# Function to calculate the salary of the person

def computeSalary( basic, grade):

hra = 0.1 * basic


da = 0.7 * basic
ta=0.3*basic
pf = 0.11 * basic

# Condition to compute the allowance for the person


if grade == 'A':
allowance = 1700.0
elif grade == 'B':
allowance = 1500.0
else:
allowance = 1300.0;

gross = round(basic + hra + da + allowance - pf)

return gross

# Driver code
if __name__ == '__main__':

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 17


basic=input(“Enter basic Salary:”)
#basic = 10000
# grade = 'A'

# Function call
print(computeSalary(basic, grade));

Experiment no 4

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 18


Exploring Basic Arithmetic Operations in Python*:

Aim-Write a Python program to explore basic arithmetic operations. The program


should prompt the user to enter two numbers and then perform addition,
subtraction, multiplication, division, and modulus operations on those numbers.
The results of each operation should be displayed to the user.

Requirement: Python 3.13.1

Program Code-

num1 = int(input('Enter First number: '))


num2 = int(input('Enter Second number '))

add = num1 + num2


dif = num1 - num2
mul = num1 * num2
div = num1 / num2
floor_div = num1 // num2
power = num1 ** num2
modulus = num1 % num2

print('Sum of ', num1, 'and', num2, 'is :', add)


print('Difference of ', num1, 'and', num2, 'is :', dif)
print('Product of ', num1, 'and', num2, 'is :', mul)
print('Division of ', num1, 'and', num2, 'is :', div)
print('Floor Division of ', num1, 'and', num2, 'is :', floor_div)
print('Exponent of ', num1, 'and', num2, 'is :', power)
print('Modulus of ', num1, 'and', num2, 'is :', modulus)

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 19


Objective:
Mastering Python New Data Structures for
Practical Applications

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 20


Experiment no 5
Task List Manager*:

Aim- Develop a Python program to manage a task list using lists and tuples,
including adding, removing, updating, and sorting tasks.

Requirement: Python 3.13.1

Program Code-

Creating Python Tuples

tup = item1, item2 ,....,item_n


tempTuple = 'apple', 'mango', 'banana'
print(tempTuple)
('apple', 'mango', 'banana')

Creating a Tuple with Mixed Datatypes

x = (2, 'apple', 3.4)


print(x)
(2, 'apple', 3.4)

Accessing Tuples

x = ("welcom", "to", "wscube", "tech")

print(x[0]) #welcom

print(x[1]) #to

print(x[2]) #wscube

print(x[3]) #tech

print(x[-1]) #tech

print(x[-2]) #wscube

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 21


print(x[-3]) #to

Nested Python Tuples

x = ((1, 2), [3, 4], 5, 6)

print(x)

Concatenation of Tuples

x = (1, 2, 3, 4)

y = (5, 6, 7, 8)

z = x + y #tuple concatenation

print(z)

Slicing of Tuple

tuple[start : stop : step]

tu = ("W", "S", "C", "U", "B", "E")

print(tu[::]) #('W', 'S', 'C', 'U', 'B', 'E')

print(tu[0::]) #('W', 'S', 'C', 'U', 'B', 'E')

print(tu[0::1]) #('W', 'S', 'C', 'U', 'B', 'E')

print(tu[2::]) #('C', 'U', 'B', 'E')

print(tu[2:6:]) #('C', 'U', 'B', 'E')

print(tu[2:6:1]) #('C', 'U', 'B', 'E')

print(tu[3:7:2]) #('U', 'E')

print(tu[::-1]) #('E', 'B', 'U', 'C', 'S', 'W')

print(tu[-2:-6:-1]) #('B', 'U', 'C', 'S')

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 22


Updating Tuples in Python

tu = ('a', 'b', 'c')

tu[0] = 'p' #will generate error

print(tu)

Deleting a Tuple

tu = ('a', 'b', 'c')

del tu[0]

print(tu)

Experiment no 6
Student Enrollment Manager *:

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 23


Aim-Create a Python code to demonstrate the use of sets and perform set operations (union, intersection,
difference) to manage student enrollments in multiple courses / appearing for multiple entrance exams
like CET, JEE, NEET etc.

# Program to perform different set operations

# as we do in mathematics

# sets are define

A = {0, 2, 4, 6, 8};

B = {1, 2, 3, 4, 5};

# union

print("Union :", A | B)

# intersection

print("Intersection :", A & B)

# difference

print("Difference :", A - B)

# symmetric difference

print("Symmetric difference :", A ^ B)

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 24


Experiment no 7
Student Record Keeper *:
Aim-Write a Python program to create, update, and manipulate a dictionary of student records, including
their grades and attendance.

# This is simplest Student data management program in python

# Create class "Student"

class Student:

# Constructor

def __init__(self, name, rollno, m1, m2):

self.name = name

self.rollno = rollno

self.m1 = m1

self.m2 = m2

# Function to create and append new student

def accept(self, Name, Rollno, marks1, marks2):

# use ' int(input()) ' method to take input from user

ob = Student(Name, Rollno, marks1, marks2)

ls.append(ob)

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 25


# Function to display student details

def display(self, ob):

print("Name : ", ob.name)

print("RollNo : ", ob.rollno)

print("Marks1 : ", ob.m1)

print("Marks2 : ", ob.m2)

print("\n")

# Search Function

def search(self, rn):

for i in range(ls.__len__()):

if(ls[i].rollno == rn):

return i

# Delete Function

def delete(self, rn):

i = obj.search(rn)

del ls[i]

# Update Function

def update(self, rn, No):

i = obj.search(rn)

roll = No

ls[i].rollno = roll

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 26


# Create a list to add Students

ls = []

# an object of Student class

obj = Student('', 0, 0, 0)

print("\nOperations used, ")

print("\n1.Accept Student details\n2.Display Student Details\n3.Search Details of a


Student\n4.Delete Details of Student\n5.Update Student Details\n6.Exit")

# ch = int(input("Enter choice:"))

# if(ch == 1):

obj.accept("A", 1, 100, 100)

obj.accept("B", 2, 90, 90)

obj.accept("C", 3, 80, 80)

# elif(ch == 2):

print("\n")

print("\nList of Students\n")

for i in range(ls.__len__()):

obj.display(ls[i])

# elif(ch == 3):

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 27


print("\n Student Found, ")

s = obj.search(2)

obj.display(ls[s])

# elif(ch == 4):

obj.delete(2)

print(ls.__len__())

print("List after deletion")

for i in range(ls.__len__()):

obj.display(ls[i])

# elif(ch == 5):

obj.update(3, 2)

print(ls.__len__())

print("List after updation")

for i in range(ls.__len__()):

obj.display(ls[i])

# else:

print("Thank You !")

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 28


Objective:
To enable students to transition
their understanding of control
statements and loops from C to
Python, emphasizing the
adoption of Python syntax while
reinforcing logical structures
already learned.

Experiment no 8

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 29


Number Type Identifier*:
Aim-Develop a Python program that takes a numerical input and identifies whether it is even or odd,
utilizing conditional statements and loops.

# Python program to check if the input number is odd or even.

# A number is even if division by 2 gives a remainder of 0.

# If the remainder is 1, it is an odd number.

num = int(input("Enter a number: "))

if (num % 2) == 0:

print("{0} is Even".format(num))

else:

print("{0} is Odd".format(num))

Experiment no 9

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 30


Factorial Generator*:
Aim-Design a Python program to compute the factorial of a given integer N.

# Input: An integer number

num = 6

# Initialize the factorial variable to 1

factorial = 1

# Calculate the factorial using a for loop

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

factorial *= i

# Output: The factorial of the number

print(f"The factorial of {num} is {factorial}")

Experiment no 10

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 31


Prime Number Analyzer*:
Aim-Using function, write a Python program to analyze the input number is prime or not.

num = 11

# Negative numbers, 0 and 1 are not primes

if num > 1:

# Iterate from 2 to n // 2

for i in range(2, (num//2)+1):

# If num is divisible by any number between

# 2 and n / 2, it is not prime

if (num % i) == 0:

print(num, "is not a prime number")

break

else:

print(num, "is a prime number")

else:

print(num, "is not a prime number")

Experiment no 11

Simple Calculator Using Functions*:

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 32


Aim-Implement a simple Python calculator that takes user input and performs basic arithmetic operations
(addition, subtraction, multiplication, division) using functions.

# Python program for simple calculator

# Function to add two numbers

def add(num1, num2):

return num1 + num2

# Function to subtract two numbers

def subtract(num1, num2):

return num1 - num2

# Function to multiply two numbers

def multiply(num1, num2):

return num1 * num2

# Function to divide two numbers

def divide(num1, num2):

return num1 / num2

print("Please select operation -\n" \

"1. Add\n" \

"2. Subtract\n" \

"3. Multiply\n" \

"4. Divide\n")

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 33


# Take input from the user

select = int(input("Select operations form 1, 2, 3, 4 :"))

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

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

if select == 1:

print(number_1, "+", number_2, "=",

add(number_1, number_2))

elif select == 2:

print(number_1, "-", number_2, "=",

subtract(number_1, number_2))

elif select == 3:

print(number_1, "*", number_2, "=",

multiply(number_1, number_2))

elif select == 4:

print(number_1, "/", number_2, "=",

divide(number_1, number_2))

else:

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 34


print("Invalid input")

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 35


Objective: To enable learners
to proficiently handle file
operations, manage exceptions,
and create Python packages and
executable files.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 36


Experiment no 12

Extracting Words from Text File *:


Aim-Develop a Python program that reads a text file and prints words of specified lengths (e.g., three,
four, five, etc.) found within the file.
# Python program to read

# file word by word

# opening the text file

with open('GFG.txt','r') as file:

# reading each line

for line in file:

# reading each word

for word in line.split():

# displaying the words

print(word)

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 37


Experiment no 13

Building an Executable File*:


Aim-Create a executable file for any program developed in earlier practical.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 38


Objective: To enable learners
to proficiently handle errors and
exceptions in Python programs,
ensuring robust and fault-
tolerant code. Learners will also
develop debugging skills to
identify, diagnose, and fix
issues efficiently using
scientific debugging methods.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 39


Experiment no 14

Basic Exception Handling*:


Aim-Write a Python program that takes two numbers as input and performs division. Implement
exception handling to manage division by zero and invalid input errors gracefully.

# Example of an exception

try:

num1 = int(input("Enter First Number: "))

num2 = int(input("Enter Second Number: "))

result = num1 / num2

print(result)

except ValueError as e:

print("Invalid Input Please Input Integer...")

except ZeroDivisionError as e:

print(e)

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 40


Experiment no 15

Using a Debugger*:
Aim-Demonstrate the use of a Python debugger (e.g., pdb or an IDE with debugging capabilities) on a
sample program with intentional errors. Guide students on setting breakpoints, stepping through code, and
examining variable values.

Debugging in Python is facilitated by pdb module (python debugger) which


comes built-in to the Python standard library. It is actually defined as the class Pdb
which internally makes use of bdb(basic debugger functions) and cmd (support for
line-oriented command interpreters) modules. The major advantage of pdb is it
runs purely in the command line, thereby making it great for debugging code on
remote servers when we don’t have the privilege of a GUI-based debugger.

pdb supports:

 Setting breakpoints

 Stepping through code

 Source code listing

 Viewing stack traces

Starting Python Debugger

There are several ways to invoke a debugger

To start debugging within the program just insert import pdb, pdb.set_trace()
commands. Run your script normally, and execution will stop where we have
introduced a breakpoint. So basically we are hard coding a breakpoint on a line
below where we call set_trace(). With python 3.7 and later versions, there is a
built-in function called breakpoint() which works in the same manner. Refer
following example on how to insert set_trace() function.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 41


Example1: Debugging a Simple Python program of addition of numbers using
Python pdb module

Intentional error: As input() returns string, the program cannot use multiplication
on strings. Thus, it’ll raise ValueError.

import pdb

def addition(a, b):

answer = a * b

return answer

pdb.set_trace()

x = input("Enter first number : ")

y = input("Enter second number : ")

sum = addition(x, y)

print(sum)

Output :

In the output on the first line after the angle bracket, we have the directory
path of our file, line number where our breakpoint is located,
and <module>. It’s basically saying that we have a breakpoint in exppdb.py
on line number 10 at the module level. If you introduce the breakpoint inside
the function, then its name will appear inside <>. The next line is showing
the code line where our execution is stopped. That line is not executed yet.
Then we have the pdb prompt. Now to navigate the code, we can use the
following commands :

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 42


Command Function

help To display all commands

where Display the stack trace and line number of the current line

Execute the current line and move to the next line ignoring function
next
calls

step Step into functions called at the current line

Now, to check the type of variable, just write whatis and variable name. In
the example given below, the output of type of x is returned as <class
string>. Thus typecasting string to int in our program will resolve the error.

Example 2: Checking variable type using pdb ‘whatis’ command


We can use ‘whatis‘ keyword followed by a variable name (locally or globally
defined) to find its type.
a = 20

b = 10

s=0

for i in range(a):

# this line will raise ZeroDivision error

s += a / b

b -= 1

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 43


 From the Command Line: It is the easiest way of using a debugger. You
just have to run the following command in terminal

python -m pdb exppdb.py (put your file name instead of exppdb.py)

This statement loads your source code and stops execution on the first line of code.

Example 3: Navigating in pdb prompt

We can navigate in pdb prompt using n (next), u (up), d (down). To debug and
navigate all throughout the Python code, we can navigate using the mentioned
commands.

a = 20

b = 10

s=0

for i in range(a):

s += a / b

b -= 1
Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 44
Output :

Example 4: Post-mortem debugging using Python pdb module


Post-mortem debugging means entering debug mode after the program is
finished with the execution process (failure has already occurred). pdb
supports post-mortem debugging through
the pm() and post_mortem() functions. These functions look for active trace
back and start the debugger at the line in the call stack where the exception
occurred. In the output of the given example, you can notice pdb appear
when an exception is encountered in the program.
def multiply(a, b):

answer = a * b

return answer

x = input("Enter first number : ")

y = input("Enter second number : ")

result = multiply(x, y)

print(result)

Output :

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 45


Checking variables on the Stack
All the variables including variables local to the function being executed in
the program as well as global are maintained on the stack. We can
use args(or use a) to print all the arguments of a function which is currently
active. p command evaluates an expression given as an argument and prints
the result.
Here, example 4 of this article is executed in debugging mode to show you
how to check for variables :

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 46


Python pdb Breakpoints
While working with large programs, we often want to add a number of
breakpoints where we know errors might occur. To do this you just have to
use the break command. When you insert a breakpoint, the debugger
assigns a number to it starting from 1. Use the break to display all the
breakpoints in the program.
Syntax:
break filename: lineno, condition
Given below is the implementation to add breakpoints in a program used for
example 4.

Managing Breakpoints
After adding breakpoints with the help of numbers assigned to them, we can
manage the breakpoints using the enable and
disable and remove command. disable tells the debugger not to stop when
that breakpoint is reached, while enable turns on the disabled breakpoints.
Given below is the implementation to manage breakpoints using Example 4.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 47


Objective: To apply object-
oriented programming (OOP)
principles in Python to model
real-world scenarios and
Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 48
systems, fostering the
development of modular,
reusable, and efficient solutions.
Fostering the ability to design
and implement solutions for
real-world problems.

Experiment 16
Online Shopping System:
Aim-Develop classes for products, customers, and shopping carts. Include methods for adding items to
the cart, calculating total costs, processing orders, and managing inventory.

In this project, you will create a system to manage the products, orders, and customers in an

online store. You will define classes to represent the store, products, orders, and customers.

Here are the steps you can follow to implement this project:

1. Start by designing the layout of the store. Decide on the types of products that you want to

include, and the information that you want to store about each product (e.g. name, price,
Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 49
description, stock). You may also want to include categories or tags to help organize your

products.

class Product:
def __init__(self, name, price, description, stock):
self.name = name
self.price = price
self.description = description
self.stock = stock

def update_stock(self, quantity):


self.stock += quantity

def total_value(self):
return self.stock * self.price

2. Created a Product class to represent the different products


in the store. The Product class should have attributes to store
the product's name, price, description, stock, and any other
relevant information. It should also have methods to update
the stock (e.g. when a product is sold or restocked), and to
calculate the total value of the product in the store (i.e. stock
x price).
class Order:
def __init__(self, customer, product, quantity):
self.customer = customer
self.product = product
self.quantity = quantity

def total_cost(self):
return self.quantity * self.product.price

3. Created an Order class to represent the orders placed by


customers. The Order class should have attributes to store the
customer, the product, and the quantity of the product being
ordered. It should also have a total_cost() method that
calculates the total cost of the order.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 50


class Customer:
def __init__(self, name, email):
self.name = name
self.email = email
self.orders = []

def place_order(self, product, quantity):


if product.stock >= quantity:
order = Order(self, product, quantity)
product.update_stock(-quantity)
self.orders.append(order)
else:
print("Error: Not enough stock")

def view_orders(self):
for order in self.orders:
print(order)

4. Created a Customer class to represent the store's customers.


The Customer class should have attributes to store the
customer's name, email address, and any other relevant
information. It should also have a place_order() method that
allows the customer to place an order for a product, and
a view_orders() method that allows the customer to view all of
their past orders.
class Store:
def init(self):
self.products = []
self.orders = []
self.customers = []

def add_product(self, product):


self.products.append(product)

def delete_product(self, product):


self.products.remove(product)

def add_customer(self, customer):


self.customers.append(customer)

def delete_customer(self, customer):


self.customers.remove(customer)

def add_order(self, order):

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 51


self.orders.append(order)

def delete_order(self, order):


self.orders.remove(order)

def find_product(self, name):


for product in self.products:
if product.name == name:
return product
return None

def find_customer(self, name):


for customer in self.customers:
if customer.name == name:
return customer
return None

def sales_report(self):
total_sales = 0
for order in self.orders:
total_sales += order.total_cost()
return total_sales

def restock_report(self):
low_stock = []
for product in self.products:
if product.stock < 10:
low_stock.append(product)
return low_stock

So finally you can check your code, test the classes.


# Test the classes
store = Store()

product1 = Product("Keyboard", 49.99, "Wireless keyboard", 100)


product2 = Product("Mouse", 29.99, "Wireless mouse", 50)
store.add_product(product1)
store.add_product(product2)

customer1 = Customer("John Smith", "john@example.com")


customer2 = Customer("Jane Doe", "jane@example.com")
store.add_customer(customer1)
store.add_customer(customer2)

customer1.place_order(product1, 1)
customer2.place_order(product2, 2)

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 52


print("Total sales:", store.sales_report())
print("Low stock:", store.restock_report())

customer1.view_orders()

This code creates a store, adds two products to the store,


adds two customers to the store, and then places two orders.
It then prints the total sales for the store and the products
with low stock, and displays the orders placed by customer1.

Objective: To develop a
graphical user interface (GUI)
application for any use case.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 53


Choose any use case from
below

Experiment 17
College Admission Registration Form:
Aim-The college admission registration form collects essential personal, educational, and contact
information from prospective students. Create a GUI as shown in Figure-1 that allows the user to input
his/her name, branch and favorite game. When the user clicks the Submit button, it should display the
output as illustrated.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 54


Figure-1: A basic GUI featuring text field and various buttons.

Program Code-

#Creating a simple GUI registration form using Tkinter in Python


#import the tkinter module into our code
from tkinter import *

#Creating the object 'base' of the Tk()


base = Tk()

#Using the Geometry method to the form certain dimensions


base.geometry("550x550")

#Using title method to give the title to the window


base.title('Registration form')

#Now, we will use 'Label' method to add widget in the Registration Form and also use place()
method to set their positions.
lbl_0 = Label(base, text="Registration form", width=20,font=("bold",20))

#the place method in tkinter module helps user to set the geometry, that is, the dimensions of a
certain widget by placing them at a certain position
lbl_0.place(x=90,y=60)

#Using 'Label' widget to create Full name label and using place() method to set its position.
lbl_1 =Label(base, text= "FullName", width=20,font=("bold",10))
lbl_1.place(x=80,y=130)

#Using Enrty widget to make a text entry box for accepting the input string in text from user.
enter_1 = Entry(base)

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 55


enter_1.place(x=240,y=130)

#Using 'Label' widget to create Email label and using place() method to set its position.
lbl_3 = Label(base, text="Email", width=20,font=("bold",10))
lbl_3.place(x=68,y=180)

#Using Enrty widget to make a text entry box for accepting the input string in text from user.
enter_3 = Entry(base)
enter_3.place(x=240,y=180)

#Using 'Label' widget to create Gender label and using place() method to set its position.
lbl_4 = Label(base, text="Gender", width=20,font=("bold",10))
lbl_4.place(x=70,y=230)

#Using variable 'vars' to store the integer value, which by deault is 0


vars = IntVar()

#Using Radio button widget to create an option choosing button and using place() method to set
its position.
Radiobutton(base, text="Male", padx= 5, variable= vars, value=1).place(x=235, y=230)
Radiobutton(base, text="Female", padx= 20, variable= vars, value=2).place(x=290,y=230)

#Using 'Label' widget to create Countries label and using place() method, set its position.
lbl_5=Label(base, text ="Country", width=20,font=("bold",11))
lbl_5.place(x=70,y=280)

#this creates list of countries available in the dropdown list.


list_of_cntry=[ 'India' ,'Canada' , 'US' ,'Germany' ,'UK']

#the variable 'cv' is introduced to store the String Value, which by default is (empty) ""
cv = StringVar()
drplist = OptionMenu(base, cv, *list_of_cntry)
drplist.config(width=15)
cv.set('Select your Country')
drplist.place(x=240, y=280)

#Using 'Label' widget to create Language label and using place() method, set its position.
lbl_6=Label(base, text="Language", width=20,font=('bold',10))
lbl_6.place(x=75,y=330)

#the new variable 'vars1' is created to store Integer Value, which by default is 0.
vars1=IntVar()
#Using the Checkbutton widget to create a button and using place() method to set its position.
Checkbutton(base,text="English", variable = vars1).place(x=230,y=330)

#the new variable 'vars1' is created to store Integer Value, which by default is 0.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 56


vars2=IntVar()
#Using the Checkbutton widget to create a button and using place() method to set its position.
Checkbutton(basetext="German", variable=vars2).place(x=290, y=330)

#Using the Button widget, we get to create a button for submitting all the data that has been
entered in the entry boxes of the form by the user.
Button(base, text='Submit' , width=20, bg="black",fg='white').place(x=180,y=380)

#Calling the mainloop method to execute the entire program.


base.mainloop()

Output:

The output for the aforementioned Simple registration form's code, using Tkinter in Python
is attached below in the form of a screenshot.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 57


Objective: To enable learners
to effectively utilize regular
expressions in Python for
pattern matching, validation,
and data extraction tasks,
enhancing their ability to
Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 58
process textual data efficiently
and accurately.

Experiment 18

Script to Validate Phone Number and Email ID *:


Aim- Write a Python script that prompts the user to enter their phone number and email ID. It then
employs Regular Expressions to verify if these inputs adhere to standard phone number and email address
formats

Program Code-

#validation of email id

import re

regex = re.compile(r'([A-Za-z0-9]+[.-_])*[A-Za-z0-9]+@[A-Za-z0-
9-]+(\.[A-Z|a-z]{2,})+')

def emailValid(email):
if re.fullmatch(regex, email):
print("The given mail is valid")
else:
print("The given mail is invalid")

emailValid("sachin.sharma@gmail.com")
emailValid("johnsnow123@yahoo.co.uk")
emailValid("mathew123@...uk")

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 59


emailValid("...@domain.us")

#validation of mobile phone number

import re

def validate_phone_number(regex, phone_number):

match = re.search(regex, phone_number)

if match:

return True

return False

pattern = re.compile(r"(\+\d{1,3})?\s?\(?\d{1,4}\)?[\s.-]?\d{3}[\s.-]?\d{4}")

test_phone_numbers = [

"+1 (555) 123-4567",

"555-123-4567",

"555 123 4567",

"+44 (0) 20 1234 5678",

"02012345678",

"invalid phone number"

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 60


]

for number in test_phone_numbers:

print(f"{number}: {validate_phone_number(pattern, number)}")

Experiment 19
Extracting Data from Text *:
Aim- Create a program that reads a text file containing various data (e.g., names, emails, phone
numbers). Use regular expressions to extract specific types of data, such as email addresses,
phone numbers, dates (e.g., MM/DD/YYYY format).

Program Code-

import re

def find_emails(text):

# List of email patterns to look for

patterns = [r"\S+@\S+"]

for pattern in patterns:

# Compile the pattern

email_regex = re.compile(pattern)

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 61


# Find all instances of the pattern in the text

emails = email_regex.findall(text)

# Print each email found

for email in emails:

print(email)

# Example usage

text = "Please send your resumes on Hr@Iwillgetbacktoyou@gmail.com" \

" for any business enquiry please mail us on business@enquiry.com" \

" and writing.geeksforgeeks.org"

find_emails(text)

Output
Hr@Iwillgetbacktoyou@gmail.com
business@enquiry.com

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 62


Objective: To equip learners
with the skills to utilize the
NumPy libraries for efficient
numerical computing.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 63


Experiment 20

Creating and Manipulating Arrays*:


Aim-Write a Python program to create a 1D, 2D, and 3D NumPy array. Perform basic operations like
reshaping, slicing, and indexing.

#Create a 1-D array containing the values 1,2,3,4,5:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

#Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])

print(arr)

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 64


#Create a 3-D array with two 2-D arrays, both containing two arrays with the
values 1,2,3 and 4,5,6:

import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])

print(arr)

Reshape From 1-D to 2-D


#Convert the following 1-D array with 12 elements into a 2-D array.

#The outermost dimension will have 4 arrays, each with 3 elements:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(4, 3)

print(newarr)

Reshape From 1-D to 3-D


#Convert the following 1-D array with 12 elements into a 3-D array.

#The outermost dimension will have 2 arrays that contains 3 arrays, each with 2
elements:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])

newarr = arr.reshape(2, 3, 2)

print(newarr)

#Slice elements from index 1 to index 5 from the following array:

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 65


import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[1:5])

#Slice elements from index 4 to the end of the array:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[4:])

#Slice from the index 3 from the end to index 1 from the end:

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[-3:-1])

Array Indexing
#Get the first element from the following array:

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[0])

#Get the second element from the following array.

import numpy as np

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 66


arr = np.array([1, 2, 3, 4])

print(arr[1])

#Get third and fourth elements from the following array and add them.

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[2] + arr[3])

#Access the element on the first row, second column:

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('2nd element on 1st row: ', arr[0, 1])

#Access the element on the 2nd row, 5th column:

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('5th element on 2nd row: ', arr[1, 4])

#Access the third element of the second array of the first array:

import numpy as np

arr = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

print(arr[0, 1, 2])

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 67


Negative Indexing

#Print the last element from the 2nd dim:

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('Last element from 2nd dim: ', arr[1, -1])

Experiment 21

Array Mathematics*:
Aim-Develop a Python script to create two arrays of the same shape and perform element-wise addition,
subtraction, multiplication, and division. Calculate the dot product and cross product of two vectors.

Python Code:
# Importing the NumPy library
import numpy as np

# Displaying a message for addition operation


print("Add:")
# Performing addition
print(np.add(1.0, 4.0))

# Displaying a message for subtraction operation


print("Subtract:")
# Performing subtraction
print(np.subtract(1.0, 4.0))

# Displaying a message for multiplication operation


print("Multiply:")
# Performing multiplication
print(np.multiply(1.0, 4.0))

# Displaying a message for division operation


print("Divide:")
# Performing division
print(np.divide(1.0, 4.0))

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 68


Sample Output:
Add:
5.0
Subtract:
-3.0
Multiply:
4.0
Divide:
0.25

# Python Program illustrating


# dot product of two vectors

# Importing numpy module


import numpy as np

# Taking two scalar values


a=5
b=7

# Calculating dot product using dot()


print(np.dot(a, b))
Output:
35

# Python Program illustrating

# dot product of two vectors

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 69


# Importing numpy module

import numpy as np

# Taking two 1D array

a = 3 + 1j

b = 7 + 6j

# Calculating dot product using dot()

print(np.dot(a, b))

Output:
(15+25j)
# Python Program illustrating

# dot product of two vectors

# Importing numpy module

import numpy as np

# Taking two 2D array

# For 2-D arrays it is the matrix product

a = [[2, 1], [0, 3]]

b = [[1, 1], [3, 2]]

# Calculating dot product using dot()

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 70


print(np.dot(a, b))

Output:
[[5 4]
[9 6]]

# Python Program illustrating

# dot product of two vectors

# Importing numpy module

import numpy as np

# Taking two 2D array

# For 2-D arrays it is the matrix product

a = [[2, 1], [0, 3]]

b = [[1, 1], [3, 2]]

# Calculating dot product using dot()

# Note that here I have taken dot(b, a)

# Instead of dot(a, b) and we are going to

# get a different output for the same vector value

print(np.dot(b, a))

Output:
[[2 4]
[6 9]]

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 71


# Python3 implementation for dot product

# and cross product of two vector.

n=3

# Function that return

# dot product of two vector array.

def dotProduct(vect_A, vect_B):

product = 0

# Loop for calculate dot product

for i in range(0, n):

product = product + vect_A[i] * vect_B[i]

return product

# Function to find

# cross product of two vector array.

def crossProduct(vect_A, vect_B, cross_P):

cross_P.append(vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1])

cross_P.append(vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2])

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 72


cross_P.append(vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0])

# Driver function

if __name__=='__main__':

vect_A = [3, -5, 4]

vect_B = [2, 6, 5]

cross_P = []

# dotProduct function call

print("Dot product:", end =" ")

print(dotProduct(vect_A, vect_B))

# crossProduct function call

print("Cross product:", end =" ")

crossProduct(vect_A, vect_B, cross_P)

# Loop that print

# cross product of two vector array.

for i in range(0, n):

print(cross_P[i], end =" ")

Output

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 73


Dot product:-4
Cross product:-49 -7 28

Experiment 22

Statistical Operations*:
Aim-Write a Python program to calculate mean, median, standard deviation, variance, and correlation
coefficients of a given array.

import numpy as np

Method 1: Using numpy.mean(), numpy.std(), numpy.var()

# Original array

array = np.arange(10)

print(array)

r1 = np.mean(array)

print("\nMean: ", r1)

r2 = np.std(array)

print("\nstd: ", r2)

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 74


r3 = np.var(array)

print("\nvariance: ", r3)

Method 2: Using the formulas

import numpy as np

# Original array

array = np.arange(10)

print(array)

r1 = np.average(array)

print("\nMean: ", r1)

r2 = np.sqrt(np.mean((array - np.mean(array)) ** 2))

print("\nstd: ", r2)

r3 = np.mean((array - np.mean(array)) ** 2)

print("\nvariance: ", r3)

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 75


Example: Comparing both inbuilt methods and formulas

import numpy as np

# Original array

x = np.arange(5)

print(x)

r11 = np.mean(x)

r12 = np.average(x)

print("\nMean: ", r11, r12)

r21 = np.std(x)

r22 = np.sqrt(np.mean((x - np.mean(x)) ** 2))

print("\nstd: ", r21, r22)

r31 = np.var(x)

r32 = np.mean((x - np.mean(x)) ** 2)

print("\nvariance: ", r31, r32)

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 76


Objective: To provide learners
with the knowledge and skills
necessary to effectively use the
Pandas library for data
manipulation and the Matplotlib
library for data visualization.
Learners will engage in tasks
that involve analyzing real-
world datasets, creating

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 77


meaningful visualizations, and
drawing insights from data.

Experiment 23
Following task should be performing on a real-world dataset:
Task1- Loading and Inspecting Data: Load a CSV file containing information on global COVID-19
cases into a DataFrame. Display the first few rows, check the data types, and summarize basic statistics.
Task 2- Data Cleaning: Identify and handle missing values in the dataset. Remove any duplicate rows
and ensure data consistency.
Task 3-Data Aggregation: Perform aggregation operations to summarize data.
Task 4- Plotting graphs: Generate a line plot showing the trend / bar plot to compare data/ histogram to
show distribution/ scatter plot to examine relationships between variables.

Python Programming Lab Manual Prepared by-Prof.Pandit T.Yewale Page 78

You might also like