0% found this document useful (0 votes)
8 views162 pages

Python STUDENT Manual

The document is a Python Programming Lab Manual for II B.Tech students, detailing the vision, mission, course outcomes, program educational objectives, and program outcomes of the Computer Science and Engineering department. It includes a comprehensive syllabus with various programming experiments covering topics such as basic I/O, decision making, loops, modules, OOPs, exceptions, data analysis, and plotting. The manual aims to equip students with the necessary skills and knowledge to meet industry demands and succeed in their careers.
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)
8 views162 pages

Python STUDENT Manual

The document is a Python Programming Lab Manual for II B.Tech students, detailing the vision, mission, course outcomes, program educational objectives, and program outcomes of the Computer Science and Engineering department. It includes a comprehensive syllabus with various programming experiments covering topics such as basic I/O, decision making, loops, modules, OOPs, exceptions, data analysis, and plotting. The manual aims to equip students with the necessary skills and knowledge to meet industry demands and succeed in their careers.
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
You are on page 1/ 162

PYTHON PROGRAMMING LAB MANUAL (R23)

(C206)

(STUDENT copy)

II B.TECH –I SEM

DEPARTMENT OF COMPUTER SCIENCE AND


ENGINEERING
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VISION
To be a pioneer in computing technologies to produce globally competent Computer Science
Engineering graduates with leadership qualities, research capabilities and ethical values to
build a vibrant society.

MISSION

 Providing a strong base in Computer Science and Engineering focusing on modern


tools and techniques to meet the global industry and higher education needs.
 Inculcating professional behavior, strong ethical values, innovative research
capabilities, and leadership abilities.
 Imparting the technical skills necessary for continued learning towards their
professional growth and contribution to society and rural communities.
Course Outcomes (CO’s)
Understand the Environment of Java Run-time Environment and
C206.1
Control Structures.

C206.2 Implement real-world objects using class Hierarchies.

C206.3 Implement programs using a collection Framework.

C206.4 Implement exception handling and file handling.

C206.5 Design GUI for real-time problems.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

PEO1: Graduates will have comprehensive knowledge in soft and technical skills to adapt the
latest tools and techniques of industry requirements in computer science engineering so that
they can analyze, design, and develop software solutions to accomplish societal needs.

PEO2: Graduates will have professional skills, leadership abilities, teamwork, and
communication skills to tackle multidisciplinary projects to succeed in their careers and
higher studies.

PEO3: Graduates will exhibit effective communication skills, collaborative abilities, and
ethical values, preparing them for successful careers, higher education, and leadership roles
in a rapidly evolving competitive environment.
PROGRAM OUTCOMES (POs)
PO1: Engineering Knowledge PO7: Environment & Sustainability
PO2: Problem Analysis PO8: Ethics
PO3: Design & Development PO9: Individual & Team Work
PO4: Investigations PO10: Communication Skills
PO5: Modern Tools PO11: Project Mgt & Finance
PO6: Engineer & Society PO12: Life Long Learning

PROGRAM SPECIFIC OUTCOMES (PSOs)


PSO1: Ability to grasp advanced programming techniques to solve contemporary issues.

PSO2: Have knowledge and expertise to analyze data and networks using latest Tools and
Technologies.

PSO3: Qualify in national and international competitive examinations for successful higher
studies and employment.
JAVA PROGRAMMING LAB SYLLABUS

Experiment 1: Programs on Basic I/O


Sample Programs
a. Demonstrate the python script by running in Interactive and Script Mode.
b. Write a python script to read using input () and display using print () functions.
c. Write a Python Program to Convert Celsius To Fahrenheit
d. Write a Python program to compute area of triangle.
e. Write a program to calculate the circumference of the circle
f. Write a Python program to compute distance between two points in a 2-dimensional
Coordinate system.
g. Write a program to swap two numbers without using a temporary variable.
h. Write a Python program that calculates number of seconds in a day
i. Write a python script to make use of all conversion functions.
j. Demonstrate the following Operators in Python with suitable examples. i) Arithmetic
Operators ii) Relational Operators iii) Assignment Operators iv) Logical Operators v)
Bit wise Operators vi) Membership Operators vii) Identity Operator.
Experiment 2: Programs on Decision Making
Sample Programs
a. Write a program to find the largest element among three Numbers.
b. Program to check whether a person is eligible to vote or not
c. Write the python script to print whether the roots are equal, distinct or complex for
given coefficients a, b and c for quadratic equation
d. Write a Program to display all prime numbers within an interval
e. Write a Python program to find the given year is leap year or not
f. Write a program to find the factorial of a given number
g. write a python program to check whether given letter is vowels or not
h. Write a python script to take five subject marks and print the grade for the student.
i. writr a python script to read the person age from user and display Person status
(1.age>60 senior citizen,2.age b/w 25 to 59 –working citizen,3.age b/w 16 to 24
college students ,4.age b/w 4 to 15 school kid,5.age b/w 1 to 3 play kid ,6.otherwise –
invalied)
j. Write a program to print the reverse of number.
Experiment 3: Programs on Loops(for ,while)
Sample Programs

a. Write a program to calculate GCD of two numbers


b. Write a Python program to print the multiplication table of a given number using a for
loop. Take the number as input from the user.
c. Write a Python program to print the first N Fibonacci numbers using a while loop.
Take N as input from the user.
d. write a program using for loop to calculate factorial of a number
e. Write a Python program using while loop to print first N numbers divisible by 5
f. Program to add natural numbers up to sum = 1+2+3+...+n
g. Write a program to take input as integer N and check whether N is Pronic Number or
not. (Product of two consecutive numbers is pronic N(N+1): Eg 110 = 10*11)
h. Write a python script to take input as amount in rupees R and find out the least
number of notes N that can be possible to store in a Wallet. (Hint Notes:
2000,500,200,100,50,20,10) Eg: R=2589, N=5
i. Write a program to check whether given number N is N-Series(Disarium) number or
not. (Eg. 135 is N-Series Number because 11+32+53 = 135 and some others are 89,
175, 518 etc)
Experiment 4: Programs Nested Loops(for ,while)
Sample Programs
a. Write a Python program to add two 3x3 matrices using nested loops. The matrices
should be predefined
b. Write a python script to print the following pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

c. Write a python script to print the following pattern


1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

d. Write a python script to take input as String S="LENDI", print the following:
L
LEL
LENEL
LENDNEL
LENDIDNEL
e. Write a python script to print the any alphabet shape using *s.
***
* *
** * *
* *
* *

Experiment 5: Programs on Modules & Functions


Sample Programs
a. Write a program to define a function with multiple return values
b. Write a python script to implement different arguments in a function.
c. Write a program to define a function using default arguments
d. Write a python program to write the content “hi python programming” for the
existing file?
e. Create a calculator module containing add, sub, mul and div and access them
f. Using Recursion, Write a program to take input as vehicle Number N and check
whether N is Fancy number or not. (Folding of digits of number should be 9)
g. Create a module named “Lendi” and create functions add Student, remove
Student, search Student. Access the above module using import statement.
h. Write a python script using lambdas, to take input as String, and sort the string SS
in descending/ascending order according to their frequency of its occurrences of
characters.(Eg. S='missisippi', SS=ispm)
i. Python program to check whether a JSON string contains complex object or not
Experiment 6: Programs Permutations & Combinations
Sample Programs
a. Write a python script to take input as number N, and find out the largest number L ,
that can be formed with N. Eg. N=679, P={679,697,769,796,967,976}, L = 976
b. Write a python script to take input as list, L and print output as largest number L and
total combinations C for given N digit number formed by the combination of L.(Eg.
L=[1,2,1,4], N=3, L=421,C=12).
c. Write a python script to print Prime pairs within a given range of numbers. (Hint
N=20, then (3,5) (5,7) (11,13) (17,19) are prime pairs)
d. By considering the terms in the Fibonacci sequence whose values do not exceed four
million, find the sum of the even-valued terms.

Experiment 7: Programs String &Regular Expressions


Sample Programs

a. Write a program to perform the given operations on a strings


i) Creating the string ii) slicing the string iii) Delete character in the string
b. Write a python script to take two string S1 and S2 and Check S1 and S2 are anagrams
or not:
c. Write a python script to take two string S1 and S2 and Check S1 is Sub string of S2 or
not
d. Write a python script to take two string S1 and S2 and check S1 is palindrome or not
e. Write a Python program to reverse a given string using a for loop. Take the string as
input from the user.
f. Write a python script to take input as multi-line string and find the sum of all numbers
in that string using re module. (Eg. S=”he11o they are 40students in97 room of 4th
line” , Sum= 152)
g. Using RegEx object check whether given phone number, email address and password
is valid or not.
h. Using date module, write a python script to take input as Date of birth (DOB) and
current date(CD) and print age of the person.

Experiment 8: Programs Lists & Dictionary


Sample Programs

a. Write a program to perform the given operations on a list:


i) Creating the list ii) slicing in the lists iii) Adding Elements in List
iv) Deleting the list elements
b. Write a program to count the number of vowels in a string(No control flow allowed).
c. Write a program to check if a given key exists in a dictionary or not.
d. Write a program to add a new key-value pair to an existing dictionary.
e. Write a program to take input as String S and print frequency of each character in S
using List data structure.
f. Write a program to take input as String S contains characters and special symbols,
reverse the String S such that special symbols remains at same position. (Eg.
S=”m@d#u” , Output=”u@d#m”).
g. Write a python script to take input as String sentence S and print each word count
using dictionary.
a. Write a python script to implement Anonymous function.
h. Write a python script to implement map(), reduce() and filter() functions
Experiment 9: Programs OOPS.
Sample Programs
a. Write a Python program to create a person class. Include attributes like name, country and
date of birth. Implement a method to determine the person's age.

b.Write a Python program to create a calculator class. Include methods for basic arithmetic
operations.
c.Write a Python program to create a class representing a shopping cart. Include methods for
adding and removing items, and calculating the total price.
d.Using Python OOPS, create a class, constructor, method, __str__ and __repr__ for
Employee
e..Using Python OOPS, create a class, constructor, method, __str__ and __repr__ for
Student
Experiment 10: Programs on Exceptions.
Sample Programs
a. Write a python program to implement Exceptions hierarchy.
b. Write a program to Catching Specific Exceptions in Python
c. Python program to try with else clause.
d. Write a Python program to handle a Zero Division Error exception when dividing
a number by zero.
e. Create a user defined Exception named “FundsLessException” and raise the
exception when there are no enough funds in the bank account.
Experiment 11: Programs Data Analysis
Sample Programs
a. Python Program to demonstrate NumPy arrays creation using array()function.
b. Python script to load data sets.
c. Write a python script to create a data frame.
d. Python program to demonstrate use of ndim, shape,size,dtype.
e. Using NumPy, implement different matrix operations in python.
f. Using pandas, read the data from any text files.
g. Python program to find min, max, sum, cumulative sum of array
h. Create a dictionary with at least five keys and each key represent value as a list where
this list contains at least ten values and convert this dictionary as a pandas data frame
and explore the data through the data frame as follows:Apply head() function to the
pandas data frame
i. Perform various data selection operations on Data Frame

Experiment 12: Programs Plotting


Sample Programs

a. Create a line plot for a list of values over a period of time. Label the x-axis as "Time"
and the y-axis as "Value".
b. Create a bar chart that shows the frequency of categories in a dataset. Use different
colors for each bar.
c. Create a histogram to visualize the distribution of a numerical dataset. Customize the
number of bins and add a title.
d. Create a scatter plot to show the relationship between two numerical variables. Add a
trend line to the scatter plot.
e. Create a pie chart to show the proportion of different categories in a dataset. Add
labels and percentages to each slice.
COURSE OUTCOMES Vs PO’s & PSO’s
SNO DESCRIPTION PO(1..12) PSO(1..3)
MAPPING MAPPING
Implement the simple Python scripts based on PO1, PO2, PO3, PSO1,PSO
C206.1 data types, operators and conditional and PO4, PO5, PO9, 2
iterative statements.[L3] PO12 PSO3
Implement various Python scripts utilizing PO1, PO2, PO3, PSO1,PSO
C206.2 built-in modules such as itertools, re, and json PO4, PO5, PO9, 2
and user-defined functions. [L3] PO12 PSO3
Implement Python scripts using fundamental PO1, PO2, PO3, PSO1,PSO
data structures like strings, lists, and PO4, PO5, PO9, 2
C206.3
dictionaries to efficiently solve different PO12 PSO3
problems. L3]
Develop Python scripts to perform PO1, PO2, PO3, PSO1,PSO
fundamental operations on diverse datasets PO4, PO5, PO9, 2
C206.4
using NumPy, Pandas, and Matplotlib for PO12 PSO3
data manipulation and visualization. [L3]
PO1,PO2,PO3,PO4, PSO1,PSO
Implement Object oriented concepts through
C206.5 PO5,PO9,PO12 2
real time scenarios and handle errors.[L3]
PSO3
C2106*COURSE OVERALL PO/PSO MAPPING: PO1,PO2,PO3,PO4,
PO5,PO9,PO12, PSO1,PSO2,PSO3

COURSE OUTCOMES VS POs MAPPING (DETAILED: HIGH: 3, MEDIUM: 2, LOW: 1)

SNO P P P P P P P P P PO PO PO PS PS PS
O O2 O3 O4 O5 O6 O7 O8 O9 10 11 12 O1 O2 O3
1
C206.1 2 2 2 2 3 3 1 2 2 2
C206.2 3 3 2 2 3 3 1 2 3 3
C206.3 3 3 2 2 2 3 1 3 2 2
C206.4 3 3 3 2 2 3 1 3 2 3
C206.5 3 3 3 3 3 3 1 3 3 3
C206.* 3 3 2 2 3 3 1 3 2 3
INDEX
WE Experiment Description CO PO/PSO Page
EK No’s
1
a. Demonstrate the python script by running in
Interactive and Script Mode.
b. Write a python script to read using input () and
display using print () functions.
c. Write a Python Program to Convert Celsius To
Fahrenheit
d. Write a Python program to compute area of
triangle.
e. Write a program to calculate the circumference of
the circle
f. Write a Python program to compute distance
PO1, PO2, PO3,
between two points in a 2-dimensional Coordinate PO4, PO5, PO9, 1-17
system. CO1
PO12 , PSO1,
g. Write a program to swap two numbers without PSO2, PSO3.
using a temporary variable.
h. Write a Python program that calculates number of
seconds in a day
i. Write a python script to make use of all conversion
functions.
j. Demonstrate the following Operators in Python
with suitable examples. i) Arithmetic Operators ii)
Relational Operators iii) Assignment Operators iv)
Logical Operators v) Bit wise Operators vi)
Membership Operators vii) Identity Operator.

2 Experiment 2: Programs on Decision Making


Sample Programs PO1, PO2, PO3,
a. Write a program to find the largest element among PO4, PO5, PO9, 18-32
CO1
three Numbers. PO12,PSO1,
b. Program to check whether a person is eligible to PSO2, PSO3.
vote or not
c. Write the python script to print whether the roots
are equal, distinct or complex for given
coefficients a, b and c for quadratic equation
d. Write a Program to display all prime numbers
within an interval
e. Write a Python program to find the given year is
leap year or not
f. Write a program to find the factorial of a given
number
g. write a python program to check whether given
letter is vowels or not
h. Write a python script to take five subject marks
and print the grade for the student.
i. writr a python script to read the person age from
user and display Person status (1.age>60 senior
citizen,2.age b/w 25 to 59 –working citizen,3.age
b/w 16 to 24 college students ,4.age b/w 4 to 15
school kid,5.age b/w 1 to 3 play kid ,6.otherwise –
invalied)
j. Write a program to print the reverse of number..

3 Experiment 3: Programs on Loops(for ,while)


Sample Programs

a. Write a program to calculate GCD of two numbers


b. Write a Python program to print the multiplication
table of a given number using a for loop. Take the
number as input from the user.
c. Write a Python program to print the first N
Fibonacci numbers using a while loop. Take N as
input from the user.
d. write a program using for loop to calculate PO1, PO2, PO3,
factorial of a number PO4, PO5, PO9,
CO1 33-46
e. Write a Python program using while loop to print PO12,PSO1,
PSO2, PSO3.
first N numbers divisible by 5
f. Program to add natural numbers up to sum =
1+2+3+...+n
g. Write a program to take input as integer N and
check whether N is Pronic Number or not.
(Product of two consecutive numbers is pronic
N(N+1): Eg 110 = 10*11)
h. Write a python script to take input as amount in
rupees R and find out the least number of notes N
that can be possible to store in a Wallet. (Hint
Notes: 2000,500,200,100,50,20,10) Eg: R=2589,
N=5
i. Write a program to check whether given number N
is N-Series(Disarium) number or not. (Eg. 135 is
N-Series Number because 11+32+53 = 135 and
some others are 89, 175, 518 etc)
4 Experiment 4: Programs Nested Loops(for ,while)
Sample Programs
a. Write a Python program to add two 3x3
matrices using nested loops. The matrices
should be predefined
b. Write a python script to print the following
pattern
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

c. Write a python script to print the following


pattern
1
2 2 PO1, PO2, PO3,
3 3 3 PO4, PO5, PO9,
CO1
PO12,PSO1, 47-57
4 4 4 4 PSO2, PSO3.
5 5 5 5 5

d. Write a python script to take input as String


S="LENDI", print the following:
L
LEL
LENEL
LENDNEL
LENDIDNEL
e. Write a python script to print the any alphabet
shape using *s.
***
* *
** * *
* *
* *
5 Experiment 5: Programs on Modules & Functions
Sample Programs
a. Write a program to define a function with
multiple return values
b. Write a python script to implement different
arguments in a function.
c. Write a program to define a function using
default arguments
d. Write a python program to write the content
“hi python programming” for the existing file?
e. Create a calculator module containing add,
sub, mul and div and access them
f. Using Recursion, Write a program to take
PO1, PO2, PO3,
input as vehicle Number N and check whether PO4, PO5, PO9,
N is Fancy number or not. (Folding of digits of CO2 58-71
PO12,PSO1,
number should be 9) PSO2, PSO3.
g. Create a module named “Lendi” and create
functions add Student, remove Student,
search Student. Access the above module using
import statement.
h. Write a python script using lambdas, to take
input as String, and sort the string SS in
descending/ascending order according to their
frequency of its occurrences of characters.(Eg.
S='missisippi', SS=ispm)
i. Python program to check whether a JSON
string contains complex object or not

6 Experiment 6: Programs Permutations &


Combinations
Sample Programs
a. Write a python script to take input as number N,
and find out the largest number L , that can be
formed with N. Eg. N=679, PO1, PO2, PO3,
P={679,697,769,796,967,976}, L = 976 PO4, PO5, PO9, 72-78
CO2
PO12,PSO1,
b. Write a python script to take input as list, L and PSO2, PSO3.
print output as largest number L and total
combinations C for given N digit number formed
by the combination of L.(Eg. L=[1,2,1,4], N=3,
L=421,C=12).
c. Write a python script to print Prime pairs within a
given range of numbers. (Hint N=20, then (3,5)
(5,7) (11,13) (17,19) are prime pairs)
d. By considering the terms in the Fibonacci
sequence whose values do not exceed four million,
find the sum of the even-valued terms.
7 Experiment 7: Programs String &Regular Expressions
Sample Programs
a. Write a program to perform the given operations
on a strings
i) Creating the string ii) slicing the string iii)
Delete character in the string
b. Write a python script to take two string S1 and S2
and Check S1 and S2 are anagrams or not:
c. Write a python script to take two string S1 and S2
and Check S1 is Sub string of S2 or not
d. Write a python script to take two string S1 and S2
PO1, PO2, PO3,
and check S1 is palindrome or not
PO4, PO5, PO9, 79-89
e. Write a Python program to reverse a given string CO3
PO12,PSO1,
using a for loop. Take the string as input from the PSO2, PSO3.
user.
f. Write a python script to take input as multi-line
string and find the sum of all numbers in that
string using re module. (Eg. S=”he11o they are
40students in97 room of 4th line” , Sum= 152)
g. Using RegEx object check whether given phone
number, email address and password is valid or
not.
h. Using date module, write a python script to take
input as Date of birth (DOB) and current date(CD)
and print age of the person.
8 Experiment 8: Programs Lists & Dictionary
Sample Programs
a. Write a program to perform the given operations
on a list:
i) Creating the list ii) slicing in the lists iii)
Adding Elements in List PO1, PO2, PO3,
iv) Deleting the list elements PO4, PO5, PO9,
CO3 90-
b. Write a program to count the number of vowels in PO12,PSO1,
100
PSO2, PSO3.
a string(No control flow allowed).
c. Write a program to check if a given key exists in a
dictionary or not.
d. Write a program to add a new key-value pair to an
existing dictionary.
e. Write a program to take input as String S and print
frequency of each character in S using List data
structure.
f. Write a program to take input as String S contains
characters and special symbols, reverse the String
S such that special symbols remains at same
position. (Eg. S=”m@d#u” , Output=”u@d#m”).
g. Write a python script to take input as String
sentence S and print each word count using
dictionary.
j. Write a python script to implement Anonymous
function.
h. Write a python script to implement map(),
reduce() and filter() functions
9 Experiment 9: Programs OOPS.
Sample Programs
a. Write a Python program to create a person class.
Include attributes like name, country and date of birth.
Implement a method to determine the person's age.

b.Write a Python program to create a calculator class.


Include methods for basic arithmetic operations. PO1, PO2, PO3,
c.Write a Python program to create a class representing a PO4, PO5, PO9,
CO5 101-
PO12,PSO1,
shopping cart. Include methods for adding and removing PSO2, PSO3. 108
items, and calculating the total price.
d.Using Python OOPS, create a class, constructor,
method, __str__ and __repr__ for
Employee
e..Using Python OOPS, create a class, constructor,
method, __str__ and __repr__ for
Student
10 Experiment 10: Programs on Exceptions.
Sample Programs
a. Write a python program to implement
Exceptions hierarchy.
b. Write a program to Catching Specific PO1, PO2, PO3,
Exceptions in Python PO4, PO5, PO9, 109-
CO5
c. Python program to try with else clause. PO12, PSO1, 119
d. Write a Python program to handle a Zero PSO2, PSO3.
Division Error exception when dividing a
number by zero.
e. Create a user defined Exception named
“FundsLessException” and raise the exception
when there are no enough funds in the bank
account.
11 Experiment 11: Programs Data Analysis
Sample Programs
a. Python Program to demonstrate NumPy arrays
creation using array()function.
b. Python script to load data sets.
c. Write a python script to create a data frame.
d. Python program to demonstrate use of ndim,
shape,size,dtype.
e. Using NumPy, implement different matrix
operations in python. PO1, PO2, PO3,
f. Using pandas, read the data from any text files. PO4, PO5, PO9, 120-
CO4
PO12, PSO1, 138
g. Python program to find min, max, sum, PSO2, PSO3.
cumulative sum of array
h. Create a dictionary with at least five keys and each
key represent value as a list where this list contains
at least ten values and convert this dictionary as a
pandas data frame and explore the data through the
data frame as follows:Apply head() function to the
pandas data frame
i. Perform various data selection operations on Data
Frame
Experiment 12: Programs Plotting
Sample Programs
12
a. Create a line plot for a list of values over a period
of time. Label the x-axis as "Time" and the y-axis
as "Value".
b. Create a bar chart that shows the frequency of
categories in a dataset. Use different colors for
each bar. PO1, PO2, PO3,
c. Create a histogram to visualize the distribution of PO4, PO5, PO9, 139-
CO4
a numerical dataset. Customize the number of bins PO12, PSO1, 144
and add a title. PSO2, PSO3.
d. Create a scatter plot to show the relationship
between two numerical variables. Add a trend line
to the scatter plot.
e. Create a pie chart to show the proportion of
different categories in a dataset. Add labels and
percentages to each slice.
Instructions to students
Pre-lab activities:
 Prepare observation note book which contains the following :
o Procedure/algorithm/program to solve the problems discussed in the theory
class
o Solutions to the exercises given in the previous lab session
 Refer the topics covered in theory class
In-lab activities:
 Note down errors observed while executing program and remedy for that.
 Note down corrections made to the code during the lab session
 Answer to vivo-voce
 Get the observation corrected
 Note down inferences on the topic covered by the programs executed
Post-lab activities:
 Solve the given exercises
 Devise possible enhancements that can be made to the solved problem to simplify the
logic
 Executed programs should be recorded in the lab record and corrected within one
week after completion of the experiment.
 After completion of every module, a test will be conducted, and assessment results
will have weight in the final internal marks.
General Instructions:
 Student should sign in the log register before accessing the system.
 Student is only responsible for any damage caused to the equipment in the laboratory
during his session.
 Usage of pen drives is not allowed in the lab.
 If a problem is observed in any hardware equipment, please report to the lab staff
immediately; do no attempt to fix the problem yourself.
 Systems must be shut down properly before leaving the lab.
 Please be considerate of those around you, especially in terms of noise level. While
labs are a natural place for conversations regarding programming, kindly keep the
volume turned down
Experiment 1: Programs on Basic I/O

1a) Demonstrate the python script by running in Interactive and Script Mode.

Aim: To understand the difference between running Python code in Interactive Mode and Script Mode.

Description:

Python provides two ways to execute code:

1. Interactive Mode: Runs commands immediately as they are entered. Useful for testing small code
snippets.

2. Script Mode: Executes a full Python script (.py file) at once. Used for writing complete programs.

This experiment demonstrates both modes and their usage.

Interactive Mode:

1. Open Python IDLE or a terminal and type python or python3.

2. Enter Python statements one by one (e.g., print("Hello, World!")).

3. Observe the immediate execution of each statement.

4. Exit Interactive Mode using exit() or Ctrl + Z (Windows) / Ctrl + D (Linux/Mac).

Script Mode:

1. Open a text editor (Notepad, VS Code, PyCharm, etc.).

2. Write a Python script and save it as script.py. Example script:

print("Hello, World!")

a=5

b = 10

sum = a + b

print("Sum:", sum)

3. Open the command prompt/terminal and navigate to the script’s location.

4. Run the script using python script.py or python3 script.py.

5. Observe the output in the terminal.


1
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Interactive Mode Output Example:

>>> print("Hello, World!")

Hello, World!

>>> a = 5

>>> b = 10

>>> a + b

15

Script Mode Output Example:

Hello, World!

Sum: 15

2
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1b)Write a python script to read using input () and display using print () functions.

Aim:

To understand how to take user input using input() and display the output using print() in Python.

Description:

 input(): A built-in function used to take input from the user. It always returns a string.

 print(): A built-in function used to display output on the console.

This experiment demonstrates reading a value from the user and printing it.

Algorithm:

1. Use input() to take user input.

2. Store the input in a variable.

3. Use print() to display the entered value.

4. Repeat the process for different types of inputs (string, integer, float).

Input:

 Name: John

 Age: 25

Expected Output:

Enter your name: John

Enter your age: 25

Hello, John! You are 25 years old.

3
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1c)Write a Python Program to Convert Celsius To Fahrenheit

Aim:

To write a Python program that converts a temperature given in Celsius to Fahrenheit .

Description:

 Temperature conversion is essential in scientific and daily life applications.

 This experiment demonstrates how to read a Celsius value from the user and convert it to
Fahrenheit using a mathematical formula.

Algorithm:

1. Prompt the user to enter a temperature in Celsius using input().

2. Convert the input from string to a floating-point number using float().

3. Apply the formula: Fahrenheit=(Celsius×9/5)+32 .

4. Display the converted Fahrenheit temperature using print().

Input:

Enter temperature in Celsius: 25

Expected Output:

Temperature in Fahrenheit: 77.0

4
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1d) Write a Python program to compute area of triangle.

Aim:

To write a Python program that calculates the area of a triangle .

Description:

 The area of a triangle can be calculated using its base and height.

 This experiment takes user input for base and height, applies the formula, and displays the result.

Algorithm:

1. Prompt the user to enter values for base and height using input().

2. Convert the input values from strings to floating-point numbers using float().

3. Apply the formula: Area=1/2×Base×Height

4. Display the computed area using print().

Input:

Enter the base of the triangle: 10

Enter the height of the triangle: 5

Expected Output:

The area of the triangle is: 25.0

5
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1e) Write a program to calculate the circumference of the circle.

Aim:

To write a Python program that calculates the circumference of a circle .

Description:

 The circumference of a circle is the total length of its boundary.

 This experiment takes radius as input, applies the formula, and displays the result.

 The value of π (pi) is used from the math module for better precision.

Algorithm:

1. Import the math module to use the constant π (pi).

2. Prompt the user to enter the radius using input().

3. Convert the input from string to a floating-point number using float().

4. Apply the formula: Circumference=2×π×radius

5. Display the computed circumference using print().

Input:

Enter the radius of the circle: 7

Expected Output:

The circumference of the circle is: 43.982297150257104

6
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1f) Write a Python program to compute distance between two points in a 2-dimensional

Coordinate system.

Aim:

To write a Python program that calculates the Euclidean distance between two points (x1,y1) and (x2,y2).

Description:

 In a 2D coordinate system, the distance between two points is computed using the Euclidean
distance formula.

 This experiment takes user input for two coordinate points, applies the formula, and displays the
result.

 The math.sqrt() function is used to calculate the square root.

Algorithm:

1. Import the math module to use sqrt().

2. Prompt the user to enter x1, y1, x2, y2 using input().

3. Convert the input values from string to floating-point numbers using float().

4. Apply the formula: Distance=(x2−x1)^2+(y2−y1)^2.

5. Display the computed distance using print().

Input:

Enter x1: 3

Enter y1: 4

Enter x2: 7

Enter y2: 1

Expected Output:

The distance between the two points is: 5.0

7
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1g) Write a program to swap two numbers without using a temporary variable.

Aim:

To write a Python program that swaps two numbers without using a temporary variable.

Description:

 Swapping means exchanging the values of two variables.

 Normally, a temporary variable is used to store one value while swapping.

 In this experiment, we swap values using arithmetic operations or Python's tuple unpacking.

Algorithm:

1. Prompt the user to enter two numbers (num1 and num2) using input().

2. Convert the input values from string to floating-point numbers using float().

3. Swap the numbers using one of the following methods:

o Arithmetic Operations: a=a+b,b=a−b,a=a−b

o Tuple Unpacking (Pythonic way): a,b=b, a

4. Display the swapped values using print().

Input:

Enter first number: 5

Enter second number: 10

Expected Output:

After swapping:

First number: 10.0

Second number: 5.0

8
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1h) Write a Python program that calculates number of seconds in a day

Aim:

To write a Python program that calculates the total number of seconds in a day using simple arithmetic
operations.

Description:

 A day consists of 24 hours.

 Each hour has 60 minutes.

 Each minute has 60 seconds.

 By multiplying these values together, we can determine the total number of seconds in one day.

Algorithm:

1. Define the number of hours in a day (24).

2. Define the number of minutes in an hour (60).

3. Define the number of seconds in a minute (60).

4. Calculate the total number of seconds using: Total Seconds=24×60×60

5. Display the computed result using print().

Input:

(No user input required, as the values are predefined.)

Expected Output:

Total number of seconds in a day: 86400

9
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1i) Write a python script to make use of all conversion functions.

Aim:

To write a Python program that demonstrates data type conversion functions in Python.

Description:

Python provides built-in functions to convert data from one type to another. The commonly used
conversion functions are:

 int(): Converts to an integer.

 float(): Converts to a floating-point number.

 str(): Converts to a string.

 bool(): Converts to a boolean.

 complex(): Converts to a complex number.

 list(), tuple(), set(), dict(): Convert between different data structures.

This experiment takes input from the user and demonstrates various conversion functions.

Algorithm:

1. Prompt the user to enter a number and a string.

2. Convert the input using different type conversion functions.

3. Display the converted values.

Input Example:

Enter a number: 5

Enter a string: Hello

Expected Output:

Conversion Results:

Integer: 5

Float: 5.0

Complex: (5+0j)
10
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Boolean: True

String: Hello

List: ['H', 'e', 'l', 'l', 'o']

Tuple: ('H', 'e', 'l', 'l', 'o')

Set: {'o', 'e', 'l', 'H'}

11
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1J) Demonstrate the following Operators in Python with suitable examples. i) Arithmetic

Operators ii) Relational Operators iii) Assignment Operators iv) Logical Operators v)

Bit wise Operators vi) Membership Operators vii) Identity Operator.

Aim:

To write a Python program that demonstrates various types of operators in Python with suitable examples.

Description:

Operators in Python are special symbols that perform operations on variables and values. Python supports
different types of operators, including:

1. Arithmetic Operators (+, -, *, /, //, %, **)

2. Relational (Comparison) Operators (==, !=, >, <, >=, <=)

3. Assignment Operators (=, +=, -=, *=, /=, %=, **=, //=)

4. Logical Operators (and, or, not)

5. Bitwise Operators (&, |, ^, ~, <<, >>)

6. Membership Operators (in, not in)

7. Identity Operators (is, is not)

This experiment demonstrates each operator with an example.

Examples:

# Define variables

a = 10

b=5

# 1. Arithmetic Operators

print("Arithmetic Operators:")

print("Addition:", a + b)
12
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
print("Subtraction:", a - b)

print("Multiplication:", a * b)

print("Division:", a / b)

print("Floor Division:", a // b)

print("Modulus:", a % b)

print("Exponentiation:", a ** b)

# 2. Relational Operators

print("\nRelational (Comparison) Operators:")

print("a == b:", a == b)

print("a != b:", a != b)

print("a > b:", a > b)

print("a < b:", a < b)

print("a >= b:", a >= b)

print("a <= b:", a <= b)

# 3. Assignment Operators

print("\nAssignment Operators:")

x = a # Assign

x += b # x = x + b

print("x after += b:", x)

x -= b

print("x after -= b:", x)

x *= b

13
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
print("x after *= b:", x)

x /= b

print("x after /= b:", x)

# 4. Logical Operators

print("\nLogical Operators:")

print("a > 5 and b < 10:", a > 5 and b < 10)

print("a > 5 or b > 10:", a > 5 or b > 10)

print("not (a > 5):", not (a > 5))

# 5. Bitwise Operators

print("\nBitwise Operators:")

print("a & b (Bitwise AND):", a & b)

print("a | b (Bitwise OR):", a | b)

print("a ^ b (Bitwise XOR):", a ^ b)

print("~a (Bitwise NOT):", ~a)

print("a << 1 (Left Shift):", a << 1)

print("a >> 1 (Right Shift):", a >> 1)

# 6. Membership Operators

print("\nMembership Operators:")

list1 = [1, 2, 3, 10, 20]

print("Is 10 in list1?", 10 in list1)

print("Is 5 not in list1?", 5 not in list1)

14
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
# 7. Identity Operators

print("\nIdentity Operators:")

x = [1, 2, 3]

y = [1, 2, 3]

z=x

print("x is z:", x is z) # True (same reference)

print("x is y:", x is y) # False (different objects)

print("x == y:", x == y) # True (same values)

print("x is not y:", x is not y) # True

Expected Output:

Arithmetic Operators:

Addition: 15

Subtraction: 5

Multiplication: 50

Division: 2.0

Floor Division: 2

Modulus: 0

Exponentiation: 100000

Relational (Comparison) Operators:

a == b: False

a != b: True

a > b: True

15
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
a < b: False

a >= b: True

a <= b: False

Assignment Operators:

x after += b: 15

x after -= b: 10

x after *= b: 50

x after /= b: 10.0

Logical Operators:

a > 5 and b < 10: True

a > 5 or b > 10: True

not (a > 5): False

Bitwise Operators:

a & b (Bitwise AND): 0

a | b (Bitwise OR): 15

a ^ b (Bitwise XOR): 15

~a (Bitwise NOT): -11

a << 1 (Left Shift): 20

a >> 1 (Right Shift): 5

Membership Operators:

16
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Is 10 in list1? True

Is 5 not in list1? True

Identity Operators:

x is z: True

x is y: False

x == y: True

x is not y: True

VIVA -VOCE QUESTIONS

1. Describe the ways of taking input .

2. List the types of operators.

3. What is the scope of input() and print()?

4. Differentiate membership operators and identity operators.

5. Explain the terms type conversion and type casting?

6. What are the features of python ?

7. Differentiate python Script and Interactive modes?

8. Differentiate logical and bitwise operators.

9. List type of datatypes.

10.Explain the differences between list and tuple.

17
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 2: Programs on Decision Making

2a) Write a program to find the largest element among three Numbers.

Aim:

To write a Python program that finds the largest number among three given numbers.

Description:

 The program takes three numbers as input from the user.

 It compares them using if-elif-else statements.

 The largest number is displayed as the output.

 Python's built-in max() function can also be used to simplify the process.

Algorithm:

1. Prompt the user to enter three numbers.

2. Convert the input values from string to float using float().

3. Compare the three numbers using:

o if num1 > num2 and num1 > num3, then num1 is the largest.

o elif num2 > num1 and num2 > num3, then num2 is the largest.

o else num3 is the largest.

4. Display the largest number.

Input Example:

Enter first number: 15

Enter second number: 20

Enter third number: 10

Expected Output:

The largest number is: 20.0

18
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
2b) Program to check whether a person is eligible to vote or not.

Aim:

To write a Python program that determines whether a person is eligible to vote based on their age.

Description:

 In most countries, the minimum voting age is 18 years.

 The program takes the person's age as input.

 If the age is 18 or above, the person is eligible to vote.

 Otherwise, they are not eligible to vote.

 The program uses an if-else statement for decision-making.

Algorithm:

1. Prompt the user to enter their age.

2. Convert the input from string to integer using int().

3. Check the condition:

o If age >= 18, print "Eligible to vote".

o Otherwise, print "Not eligible to vote".

Input Example 1:

Enter your age: 20

Expected Output 1:

You are eligible to vote.

Input Example 2:

Enter your age: 16

Expected Output 2:

You are not eligible to vote.

19
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
2c) Write the python script to print whether the roots are equal, distinct or complex for

given coefficients a, b and c for quadratic equation.

Aim:

To write a Python program that determines whether the roots of a quadratic equation are equal, distinct, or
complex based on the given coefficients.

Description:

A quadratic equation is of the form:

x^2 + bx + c = 0

where a, b, c are coefficients.

The nature of the roots is determined using the discriminant:

D=b2−4acD = b^2 - 4ac

 If D>0D > 0 → Roots are real and distinct.

 If D=0D = 0 → Roots are real and equal.

 If D<0D < 0 → Roots are complex (imaginary).

Algorithm:

1. Prompt the user to enter the coefficients a, b, c.

2. Compute the discriminant DD using D=b2−4acD = b^2 - 4ac.

3. Use conditions to check:

o If D>0D > 0, print "Roots are real and distinct".

o If D=0D = 0, print "Roots are real and equal".

o If D<0D < 0, print "Roots are complex".

Input Example 1 (Distinct Roots):

Enter coefficient a: 1

Enter coefficient b: -5
20
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Enter coefficient c: 6

Expected Output:

Roots are real and distinct.

(Since D = (-5)^2 - 4(1)(6) = 25 - 24 = 1 > 0)

Input Example 2 (Equal Roots):

Enter coefficient a: 1

Enter coefficient b: -4

Enter coefficient c: 4

Expected Output:

Roots are real and equal.

Input Example 3 (Complex Roots):

Enter coefficient a: 1

Enter coefficient b: 2

Enter coefficient c: 5

Expected Output:

Roots are complex (imaginary).

21
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
2d) Write a Program to display all prime numbers within an interval.

Aim:

To write a Python program that prints all prime numbers within a given interval.

Description:

A prime number is a natural number greater than 1 that is divisible only by 1 and itself.
For example, 2, 3, 5, 7, 11, 13 are prime numbers.

The program takes two inputs:

 The starting number of the interval.

 The ending number of the interval.


It then checks each number in the range and prints the prime numbers.

Algorithm:

1. Take two inputs start and end from the user.

2. Loop through all numbers in the range [start, end].

3. For each number, check if it is prime using the following logic:

o If the number is less than 2, skip it.

o If the number is divisible by any number from 2 to sqrt(n), it is not prime.

4. Print all the prime numbers found.

Input Example:

Enter the starting number: 10

Enter the ending number: 30

Expected Output:

Prime numbers between 10 and 30 are: 11 13 17 19 23 29

22
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
2e) Write a Python program to find the given year is leap year or not.

Aim:

To write a Python program that determines whether a given year is a leap year or not.

Description:

A leap year occurs every four years to keep the calendar in sync with the Earth's orbit.
The rules to determine a leap year are:

1. A year is a leap year if it is divisible by 4.

2. However, if the year is also divisible by 100, it is not a leap year.

3. But if the year is divisible by 400, then it is a leap year.

Algorithm:

1. Take an input year from the user.

2. Check the conditions:

o If year % 400 == 0, it is a leap year.

o Else, if year % 100 == 0, it is not a leap year.

o Else, if year % 4 == 0, it is a leap year.

o Otherwise, it is not a leap year.

3. Display the result.

Input Example 1 (Leap Year):

Enter a year: 2024

Expected Output:

2024 is a Leap Year.

Input Example 2 (Not a Leap Year):

Enter a year: 1900

Expected Output:

1900 is NOT a Leap Year.


23
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
2f) Write a program to find the factorial of a given number.

Aim:

To write a Python program that calculates the factorial of a given number.

Description:

The factorial of a number n (denoted as n!) is the product of all positive integers from 1 to n.

n!=n×(n−1)×(n−2)×⋯×2×1

For example:

 5! = 5 × 4 × 3 × 2 × 1 = 120

 4! = 4 × 3 × 2 × 1 = 24

 1! = 1

 0! = 1 (By definition)

The program calculates the factorial using a loop and an alternative method using recursion.

Algorithm (Using Loop):

1. Take an input number n from the user.

2. Initialize factorial = 1.

3. Use a for loop from 1 to n:

o Multiply the value of factorial by the loop variable.

4. Print the calculated factorial.

Input Example 1:

Enter a number: 5

Expected Output:

The factorial of 5 is 120.

Input Example 2 (Edge Case for 0):

Enter a number: 0

24
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Expected Output:

The factorial of 0 is 1.

25
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
2g)write a python program to check whether given letter is vowels or not.

Aim:

To write a Python program that determines whether a given letter is a vowel or not.

Description:

The English vowels are:


A, E, I, O, U (both uppercase and lowercase).

The program takes a single letter as input and checks whether it belongs to the set of vowels.
If it is in {a, e, i, o, u, A, E, I, O, U}, it prints "Vowel", otherwise, it prints "Not a Vowel".

Algorithm:

1. Take an input letter from the user.

2. Convert it to lowercase to handle both uppercase and lowercase inputs.

3. Check if the letter is in the set {a, e, i, o, u}.

4. If yes, print "Vowel".

5. Otherwise, print "Not a Vowel".

Input Example 1:

Enter a letter: A

Expected Output:

a is a Vowel.

Input Example 2:

Enter a letter: z

Expected Output:

z is Not a Vowel.

26
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
2h) Write a python script to take five subject marks and print the grade for the student.

Aim:

To write a Python program that takes marks of five subjects as input and calculates the grade based on the
total percentage.

Description:

The program calculates the total marks and percentage, then assigns a grade based on the following criteria:

Percentage (%) Grade

≥ 90 A+

80 - 89 A

70 - 79 B

60 - 69 C

50 - 59 D

< 50 Fail

Algorithm:

1. Take input marks for five subjects.

2. Compute total marks and percentage using:


Percentage=(Total MarksMaximum Marks)×100\text{Percentage} = \left(\frac{\text{Total
Marks}}{\text{Maximum Marks}}\right) \times 100

3. Compare the percentage with grading criteria and assign a grade.

4. Print the total marks, percentage, and grade.

Input Example:

Enter marks for Subject 1: 85

Enter marks for Subject 2: 90

Enter marks for Subject 3: 78

Enter marks for Subject 4: 88


27
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Enter marks for Subject 5: 92

Expected Output:

----- Student Result -----

Total Marks: 433/500

Percentage: 86.60%

Grade: A

28
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
2i) write a python script to read the person age from user and display Person status

(1.age&gt;60 senior citizen,2.age b/w 25 to 59 –working citizen,3.age b/w 16 to 24

college students ,4.age b/w 4 to 15 school kid,5.age b/w 1 to 3 play kid ,6.otherwise

–invalied)

Aim:

To write a Python program that reads a person's age from the user and categorizes them into different status
groups.

Description:

The program takes age as input and determines the status based on the following criteria:

Age Range Status

> 60 Senior Citizen

25 - 59 Working Citizen

16 - 24 College Student

4 - 15 School Kid

1-3 Play Kid

Other Invalid Age

Algorithm:

1. Take age as input from the user.

2. Use if-elif-else conditions to classify the person:

o If age > 60, print "Senior Citizen".

o If 25 ≤ age ≤ 59, print "Working Citizen".

o If 16 ≤ age ≤ 24, print "College Student".

o If 4 ≤ age ≤ 15, print "School Kid".

o If 1 ≤ age ≤ 3, print "Play Kid".


29
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
o Otherwise, print "Invalid Age".

3. Display the person’s status.

Input Example 1 (Working Citizen):

Enter your age: 30

Expected Output:

Person's Status: Working Citizen

Input Example 2 (Invalid Age):

Enter your age: -5

Expected Output:

Person's Status: Invalid Age.

30
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
2j) Write a program to print the reverse of number.

Aim:

To write a Python program that takes an integer number as input and prints its reverse.

Description:

Reversing a number means writing its digits in reverse order.


For example:

 Input: 1234 → Output: 4321

 Input: 9876 → Output: 6789

This can be achieved using mathematical operations or string manipulation.

Algorithm (Using Mathematical Operations):

1. Take an integer number as input.

2. Initialize reverse = 0.

3. Use a while loop to extract digits:

o Get the last digit using num % 10.

o Add it to reverse after multiplying it by 10.

o Remove the last digit using num = num // 10.

4. Repeat until num becomes 0.

5. Print the reversed number.

Input Example 1:

Enter a number: 1234

Expected Output:

Reversed Number: 4321

Input Example 2 (Negative Number):

Enter a number: -9876

Expected Output:
31
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Reversed Number: -6789

VIVA -VOCE QUESTIONS

1. What is the purpose of the if statement in Python?

2. What is the difference between if, elif , and else in Python?

3. How does Python handle boolean expressions in decision-making?

4. What is the purpose of the in operator in decision-making?

5. How can you make decisions using the try, except block in Python?

6. Explain while loop in python.

7. Explain various syntaxes of for loop in python.

8. Differentiate between ‘==’ and ‘is’ operators

9. Explain the importance of Indentation

32
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 3: Programs on Loops(for ,while)

3a)Write a program to calculate GCD of two numbers.

Aim:

To write a Python program that computes the Greatest Common Divisor (GCD) of two numbers.

Description:

The GCD (Greatest Common Divisor) of two numbers is the largest number that divides both numbers
exactly.

For example:

 GCD of 12 and 18 → 6 (because 6 is the largest number that divides both 12 and 18)

 GCD of 81 and 27 → 27

The program calculates the GCD using two different approaches:

1. Using Loops (Basic Method)

2. Using math.gcd() Function (Optimized Method)

Algorithm (Using Loops):

1. Take two numbers as input.

2. Find the smallest number among them.

3. Start a loop from 1 to that smallest number.

4. Check if both numbers are divisible by the current loop value.

5. Update the GCD variable when a common divisor is found.

6. Print the GCD after the loop ends.

Input Example:

Enter first number: 12

Enter second number: 18

Expected Output:

GCD of 12 and 18 is 6
33
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
3b)Write a Python program to print the multiplication table of a given number using a for loop. Take
the number as input from the user.

Aim:

To write a Python program that takes a number as input from the user and prints its multiplication table
using a for loop.

Description:

A multiplication table of a number N consists of its multiples from 1 to 10.


For example, the multiplication table of 5 is:

5×1 =5

5 × 2 = 10

5 × 3 = 15

5 × 4 = 20

5 × 5 = 25

5 × 6 = 30

5 × 7 = 35

5 × 8 = 40

5 × 9 = 45

5 × 10 = 50

The program takes an integer number as input and prints its multiplication table from 1 to 10.

Algorithm:

1. Take an integer N as input from the user.

2. Use a for loop to iterate from 1 to 10.

3. Multiply N by the loop variable and print the result in the format:

N × i = result

4. Repeat until i = 10.

Input Example:
34
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Enter a number: 5

Expected Output:

Multiplication Table of 5:

5×1=5

5 × 2 = 10

5 × 3 = 15

5 × 4 = 20

5 × 5 = 25

5 × 6 = 30

5 × 7 = 35

5 × 8 = 40

5 × 9 = 45

5 × 10 = 50

35
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
3c)Write a Python program to print the first N Fibonacci numbers using a while loop. Take N as input
from the user.

Aim:

To write a Python program that takes N as input and prints the first N Fibonacci numbers using a while loop.

Description:

The Fibonacci sequence is a series of numbers where:

 The first two numbers are 0 and 1.

 Each next number is the sum of the two preceding numbers.

The sequence follows this pattern:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

For example, if N = 7, the output should be:

0, 1, 1, 2, 3, 5, 8

Algorithm:

1. Take N as input from the user.

2. Initialize the first two Fibonacci numbers:

first = 0, second = 1

3. Print the first N Fibonacci numbers using a while loop:

o Print first number.

o Update first and second using:

next = first + second

first = second

second = next

o Repeat until N numbers are printed.

Input Example:

Enter the number of Fibonacci numbers to print: 7


36
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Expected Output:

Fibonacci Sequence:

0112358

37
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
3d)write a program using for loop to calculate factorial of a number.

Aim:

To write a Python program that takes an integer number as input and calculates its factorial using a for loop.

Description:

The factorial of a number N is the product of all positive integers from 1 to N. It is denoted as N!.
Mathematically,

N! = N × (N-1) × (N-2) × ... × 2 × 1

For example:

 5! = 5 × 4 × 3 × 2 × 1 = 120

 3! = 3 × 2 × 1 = 6

 1! = 1

 0! = 1 (by definition)

Algorithm:

1. Take an integer N as input.

2. Initialize factorial = 1.

3. Use a for loop to iterate from 1 to N.

4. Multiply factorial by each number in the loop.

5. Print the final factorial value.

Input Example:

Enter a number: 5

Expected Output:

Factorial of 5 is 120

38
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
3e)Write a Python program using while loop to print first N numbers divisible by 5.

Aim:

To write a Python program that takes N as input and prints the first N numbers that are divisible by 5 using
a while loop.

Description:

A number is divisible by 5 if it is a multiple of 5 (i.e., num % 5 == 0).


For example, the first 6 numbers divisible by 5 are:

5, 10, 15, 20, 25, 30

The program takes an integer N from the user and prints the first N multiples of 5.

Algorithm:

1. Take an integer N as input.

2. Initialize count = 0 and num = 5.

3. Use a while loop to print N numbers divisible by 5:

o Print num (current multiple of 5).

o Increment count by 1.

o Increase num by 5.

o Repeat until count == N.

Input Example:

Enter the number of multiples of 5 to print: 6

Expected Output:

First 6 numbers divisible by 5:

5 10 15 20 25 30

39
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
3f)Program to add natural numbers up to sum = 1+2+3+...+n.

Aim:

To write a Python program that takes an integer N as input and calculates the sum of the first N natural
numbers using a loop.

Description:

A natural number is a positive integer (1, 2, 3, ...).


The sum of the first N natural numbers follows the formula:

S=1+2+3+...+N=N×(N+1)2S = 1 + 2 + 3 + ... + N = \frac{N \times (N + 1)}{2}S=1+2+3+...+N=2N×(N+1)

For example:

 If N = 5, then

S=1+2+3+4+5=15

 If N = 10, then

S=1+2+...+10=55

Algorithm:

1. Take N as input from the user.

2. Initialize sum = 0.

3. Use a for loop to iterate from 1 to N:

o Add each number to sum.

4. Print the final sum.

Input Example:

Enter a positive integer: 5

Expected Output:

Sum of first 5 natural numbers is 15

40
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
3g)Write a program to take input as integer N and check whether N is Pronic Number or not. (Product
of two consecutive numbers is pronic N(N+1): Eg 110 = 10*11)

Aim:

To write a Python program that takes an integer N as input and checks whether it is a Pronic Number or not.

Description:

A Pronic Number (also called a Rectangular Number or Heteromecic Number) is a number that is the
product of two consecutive integers:

N=k×(k+1)N = k \times (k + 1)N=k×(k+1)

For example:

 6 = 2 × 3 → Pronic

 12 = 3 × 4 → Pronic

 20 = 4 × 5 → Pronic

 110 = 10 × 11 → Pronic

 15 is not a pronic number.

Algorithm:

1. Take N as input from the user.

2. Initialize k = 0.

3. Use a while loop to check if k * (k + 1) == N:

o If true, N is a Pronic Number.

o If k * (k + 1) > N, break the loop (since numbers beyond this won't work).

o Otherwise, increase k by 1 and continue checking.

4. Print the result accordingly.

Input Example 1:

Enter an integer: 110

Expected Output 1:

41
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
110 is a Pronic Number (10 * 11 = 110)

Input Example 2:

Enter an integer: 15

Expected Output 2:

15 is NOT a Pronic Number

42
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
3h)Write a python script to take input as amount in rupees R and find out the least number of notes N
that can be possible to store in a Wallet. (Hint Notes: 2000,500,200,100,50,20,10) Eg: R=2589, N=5.

Aim:

To write a Python program that takes an amount R (in rupees) as input and calculates the minimum number
of currency notes required to make up the amount using available denominations.

Description:

Indian currency notes available:


₹2000, ₹500, ₹200, ₹100, ₹50, ₹20, ₹10

The goal is to use the least number of notes to represent a given amount R.

For example, if R = 2589, the optimal way to get this amount is:

 1 × ₹2000

 1 × ₹500

 0 × ₹200

 0 × ₹100

 1 × ₹50

 1 × ₹20

 1 × ₹10

 Total Notes = 5

Algorithm:

1. Take R (amount in rupees) as input.

2. Define a list of available notes: [2000, 500, 200, 100, 50, 20, 10].

3. Initialize total_notes = 0.

4. Iterate through each denomination:

o Find how many notes of that denomination can fit into R.

o Reduce R by the equivalent amount.

o Increase the count of total notes.


43
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
5. Print the total number of notes and their breakdown.

Input Example:

Enter the amount in rupees: 2589

Expected Output:

Minimum number of notes required: 5

Notes breakdown:

₹2000 x 1

₹500 x 1

₹50 x 1

₹20 x 1

₹10 x 1

44
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
3i)Write a program to check whether given number N is N-Series(Disarium) number or not. (Eg. 135 is
N-Series Number because 1 1 +3 2 +5 3 = 135 and some others are 89, 175, 518 etc).

Aim:

To write a Python program that takes an integer N as input and checks whether it is an N-Series (Disarium)
Number or not.

Description:

A Disarium Number (or N-Series Number) is a number in which the sum of its digits, each raised to the
power of its position (starting from 1), is equal to the original number.

Mathematically,

N=d1^1+d2^2+d3^3+⋯+dn^n

where d₁, d₂, ..., dₙ are the digits of N, and their powers are determined by their positions.

Example:

135 is a Disarium Number because:

1^1 + 3^2 + 5^3 = 1 + 9 + 125 = 13511+32+53=1+9+125=135

89 is a Disarium Number because:

8^1 + 9^2 = 8 + 81 = 8981+92=8+81=89

80 is not a Disarium Number because:

Algorithm:

1. Take N as input from the user.

2. Convert N into a string to access digits and positions.

3. Initialize sum_digits = 0.

4. Iterate through each digit:

o Convert it to an integer.

o Raise it to the power of its position (starting from 1).

o Add the result to sum_digits.


45
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
5. If sum_digits == N, print that N is a Disarium Number.

6. Otherwise, print that N is NOT a Disarium Number.

Input Example 1:

Enter an integer: 135

Expected Output 1:

135 is a Disarium Number

Input Example 2:

Enter an integer: 80

Expected Output 2:

80 is NOT a Disarium Number

VIVA - VOCE QUESTIONS

1.What is a pronic number?

2. What is a disarium number?

3. What are the different types of loops in Python?

4. How does a for loop work in Python?

5. How does a while loop work in Python?

6. What is the difference between a for loop and a while loop?

7. How do you use a for loop to iterate over a list?  How can you loop through a dictionary?

8. What is the use of the break and continue statement in loops?

9. How do you use the else block with loops in Python?

10. How can you use a loop with the range() function?

46
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 4: Programs Nested Loops(for ,while)

4a)Write a Python program to add two 3x3 matrices using nested loops. The matrices should be
predefined.

Aim:

To write a Python program to add two 3×3 matrices using nested loops, where the matrices are predefined.

Description:

A matrix is a rectangular array of numbers arranged in rows and columns.


The sum of two matrices is computed by adding corresponding elements.

For two 3×3 matrices:

A=[ [a11 a12 a13 ]

[a21 a22 a23 ]

[a31 a32 a33] ]

B=[ [b11 b12 b13]

[b21 b22 b23]

[b31 b32 b33] ]

The resulting matrix C after addition is:

C=[ [a11+b11 a12+b12 a13+b13]

[a21+b21 a22+b22 a23+b23]

[a31+b31 a32+b32 a33+b33] ]

Algorithm:

1. Define two 3×3 matrices as lists of lists.

2. Initialize an empty 3×3 matrix for storing the sum.

3. Use nested loops:

o The outer loop iterates over rows (i).

o The inner loop iterates over columns (j).

47
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
o Add corresponding elements and store in the result matrix.

4. Print the resulting matrix.

Input:

A=[

[1, 2, 3],

[4, 5, 6],

[7, 8, 9]

B=[

[9, 8, 7],

[6, 5, 4],

[3, 2, 1]

Expected Output:

Matrix A:

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]

Matrix B:

[9, 8, 7]

[6, 5, 4]

[3, 2, 1]

48
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Sum of A and B (Matrix C):

[10, 10, 10]

[10, 10, 10]

[10, 10, 10]

49
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
4b)Write a python script to print the following pattern .

12

123

1234

12345

Aim:

To write a Python script that prints the following pattern using loops:

12

123

1234

12345

Description:

This program generates a triangular number pattern, where each row contains numbers starting from 1 up
to the row number. The pattern follows these rules:

 Row 1 → Print 1

 Row 2 → Print 1 2

 Row 3 → Print 1 2 3

 Row 4 → Print 1 2 3 4

 Row 5 → Print 1 2 3 4 5

This can be achieved using nested loops, where:

 The outer loop controls the number of rows.

 The inner loop prints numbers from 1 to the current row number.

Algorithm:
50
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1. Take N (number of rows) as input.

2. Use a for loop to iterate from 1 to N.

3. Inside the loop, use another for loop to print numbers from 1 to the current row number.

4. Print a newline after each row.

Input:

Enter the number:5

Expected Output:

12

123

1234

12345

51
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
4c)Write a python script to print the following pattern

22

333

4444

55555

Aim:

To write a Python script that prints the following pattern using loops:

22

333

4444

55555

Description:

This program generates a triangular number pattern, where:

 Each row number is printed that many times.

 The row number determines both the number of elements and their values.

Example breakdown:

 Row 1: Print 1 once

 Row 2: Print 2 twice

 Row 3: Print 3 three times

 Row 4: Print 4 four times

 Row 5: Print 5 five times

This can be achieved using nested loops:

52
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
 The outer loop controls the number of rows.

 The inner loop prints the row number repeatedly.

Algorithm:

1. Take N (number of rows) as input.

2. Use a for loop to iterate from 1 to N.

3. Inside the loop, use another for loop to print the row number i times.

4. Print a newline after each row.

Input:

Enter the number:5

Expected Output:

22

333

4444

55555

53
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
4d) Write a python script to take input as String S=&quot;LENDI&quot;, print the following:

LEL

LENEL

LENDNEL

LENDIDNEL

Aim:

To write a Python script that takes input as S = "LENDI" and prints the following pattern in a center-aligned
format:

LEL

LENEL

LENDNEL

LENDIDNEL

Description:

 The given string is "LENDI".

 The pattern follows a mirrored triangular structure where:

o The first part of each row consists of the first i characters of S.

o The second part mirrors the first part in reverse (excluding the last repeated character).

o Each row is center-aligned, meaning spaces (" ") are added to shift the pattern.

For S = "LENDI", the pattern is generated as follows:

 Row 1: " L"

 Row 2: " LEL"

 Row 3: " LENEL"

 Row 4: " LENDNEL"


54
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
 Row 5: "LENDIDNEL"

Algorithm:

1. Take the input string S = "LENDI".

2. Find the length of S (N).

3. Use a for loop to iterate from 1 to N.

4. Extract the first i characters from S.

5. Append the reverse of the substring (excluding the last character).

6. Center-align each row by adding leading spaces.

7. Print the generated pattern row by row.

Input:

Enter the string: LENDI

Expected Output:

LEL

LENEL

LENDNEL

LENDIDNEL

55
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
4e) Write a python script to print the any alphabet shape using *s.

Aim:

To write a Python script that prints a specific alphabet shape using * characters.

Given Pattern:

This pattern represents the letter "A".

Description:

 The first row has three * in the center.

 The middle rows have * at the edges, creating a hollow structure.

 The third row has all *, forming the horizontal bar of "A".

 The pattern follows a fixed width where spaces are used for alignment.

Algorithm:

1. Initialize the dimensions of the pattern:

o Set rows = 5 and cols = 5.

2. Loop through each row (i) from 0 to rows - 1:

o For each row, loop through each column (j) from 0 to cols - 1.

56
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
3. Apply conditions to print * or spaces (" "):

o If i == 0 and 1 ≤ j ≤ 3: Print * (Top three * forming the peak).

o If i == 2: Print * in all columns (Horizontal middle bar of "A").

o If j == 0 or j == 4: Print * (Side edges of "A").

o Otherwise, print " " (Space to create the hollow effect).

4. Print a new line (print()) after each row to move to the next line.

Expected Output:

VIVA - VOCE QUESTIONS

1. What is a nested loop in Python?


2. How does a nested for loop work?
3. Can you use a while loop inside a for loop?
4. Can you use a for loop inside a while loop?
5. What is the syntax for a nested loop in Python?
6. How do you iterate over a 2D list (list of lists) using nested loops?
7. How can you use nested loops to generate a multiplication table?
8. What happens when a break statement is used inside a nested loop?
9. What happens when a continue statement is used inside a nested loop?
10. How can you print a pattern (e.g., a pyramid or triangle) using nested loops?

57
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 5: Programs on Modules &amp; Functions

5a)Write a program to define a function with multiple return values.

Aim:

To write a Python program that defines a function capable of returning multiple values.

Description:

 In Python, functions can return multiple values by using tuples.

 This experiment demonstrates defining a function that performs multiple calculations and returns
multiple results.

 We will write a function to perform arithmetic operations (addition, subtraction, multiplication, and
division) on two numbers and return all results.

Algorithm:

1. Define a function that accepts two numbers as parameters.

2. Perform multiple calculations (addition, subtraction, multiplication, division).

3. Return all results as multiple values (tuple).

4. Call the function with user-input values.

5. Store the returned values and print them.

Input:

Enter first number: 10

Enter second number: 5

Expected Output:

Addition: 15.0

Subtraction: 5.0

Multiplication: 50.0

Division: 2.0

58
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
5b)Write a python script to implement different arguments in a function.

Aim:

To write a Python script that demonstrates the use of different types of arguments in a function.

Description:

Python supports multiple types of function arguments:

1. Positional Arguments – Passed in order.

2. Default Arguments – Have a default value if not provided.

3. Keyword Arguments – Specified by name, making them more readable.

4. Variable-Length Arguments (*args and **kwargs) – Used when the number of arguments is unknown.

We will define a function that demonstrates all these types of arguments.

Algorithm:

1. Define a function with different argument types:

o A positional argument for required input.

o A default argument with a fallback value.

o A variable-length argument (*args) for additional numbers.

o A keyword argument (**kwargs) to accept key-value pairs.

2. Pass various arguments while calling the function.

3. Print results to demonstrate each type of argument.

Expected Output:

Example 1: Passing all argument types

Positional Argument: Required

Default Argument: Custom Default

Additional Positional Arguments (*args): (10, 20, 30)

Keyword Arguments (**kwargs): {'key1': 'Value1', 'key2': 'Value2'}

59
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Example 2: Using only required and default arguments

Positional Argument: Required

Default Argument: Default

Example 3: Using *args for multiple values

Positional Argument: Required

Default Argument: Custom Default

Additional Positional Arguments (*args): (5, 15, 25)

Example 4: Using **kwargs for named parameters

Positional Argument: Required

Default Argument: Default

Keyword Arguments (**kwargs): {'key1': 'Apple', 'key2': 'Banana'}

60
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
5c)Write a program to define a function using default arguments.

Aim:

To write a Python program that defines a function using default arguments.

Description:

 Default arguments in Python allow functions to have predefined values.

 If an argument is not passed while calling the function, the default value is used.

 This makes functions more flexible and reduces the need for handling missing arguments.

 We will write a function to calculate the total price of an item, where the default values are:

o quantity = 1 (if not specified).

o tax = 5% (if not specified).

Algorithm:

1. Define a function with default arguments:

o price (mandatory argument).

o quantity=1 (default quantity is 1).

o tax=0.05 (default tax is 5%).

2. Calculate the total cost as:

total=price×quantity+(price×quantity×tax)

3. Return the final total cost.

4. Call the function with different argument combinations.

5. Print the results for each case.

Expected Output:

Example 1: Using all default arguments

Total Price: 105.0

61
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Example 2: Custom quantity, default tax

Total Price: 315.0

Example 3: Custom quantity and tax

Total Price: 220.0

62
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
5d)Write a python program to write the content “hi python programming” for the existing file?

Aim:

To write the content "hi python programming" to an existing file in Python.

Description:

 Python provides file handling functions such as open(), write(), and close() to work with files.

 The open() function allows us to open a file in different modes:

o "w" (write mode): Overwrites the file if it exists.

o "a" (append mode): Adds content to the file without deleting the existing content.

 This program writes the text "hi python programming" into an existing file.

Algorithm:

1. Open the file in write mode ("w") or append mode ("a").

2. Write the content "hi python programming" to the file.

3. Close the file to save changes.

4. Reopen the file in read mode ("r") to verify the content.

5. Print the content of the file to confirm.

Expected Output:

Content written successfully to example.txt

File Content After Writing:

hi python programming

63
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
5e)Create a calculator module containing add, sub, mul and div and access them.

Aim:

To create a calculator module containing add, subtract, multiply, and divide functions and access them in
another Python script.

Description:

 Modules in Python allow us to reuse code by defining functions in a separate file (.py).

 We create a custom module named calculator.py containing functions for basic arithmetic operations.

 Then, we will import and use these functions in another script.

Algorithm:

1. Create a new Python file named calculator.py.

2. Define four functions inside calculator.py:

o add(a, b) → Returns a + b.

o sub(a, b) → Returns a - b.

o mul(a, b) → Returns a * b.

o div(a, b) → Returns a / b, handling division by zero.

3. Save the module in the same directory.

4. Create another script (main.py) to import and use the module.

5. Call the functions and display the results.

Expected Output (Example Run)

Enter first number: 10

Enter second number: 5

Results:

Addition: 15.0
64
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Subtraction: 5.0

Multiplication: 50.0

Division: 2.0

65
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
5f)Using Recursion, Write a program to take input as vehicle Number N and check whether N is Fancy
number or not. (Folding of digits of number should be 9).

Aim:

To write a recursive Python program that checks whether a given vehicle number N is a Fancy Number
(Folding sum of digits should be 9).

Description:

 A Fancy Number is defined as a number where the sum of digits is repeatedly folded until a single
digit remains, and that digit should be 9.

 Example:

o N = 99918

o Sum of digits: 9 + 9 + 9 + 1 + 8 = 36

o Sum of digits of 36: 3 + 6 = 9 ✅ (Fancy Number)

 We use recursion to repeatedly calculate the sum of digits until a single digit remains.

 If the final single-digit sum is 9, the number is a Fancy Number.

Algorithm:

1. Define a recursive function digit_sum(n) that:

o If n is a single-digit, return n.

o Otherwise, compute the sum of digits and recursively call digit_sum().

2. Take vehicle number N as input.

3. Call digit_sum(N) to get the final folded sum.

4. Check if the final sum is 9:

o If yes, print "Fancy Number".

o Otherwise, print "Not a Fancy Number".

Expected Output:

66
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Example 1:

Enter the vehicle number: 99918

99918 is a Fancy Number

Example 2:

Enter the vehicle number: 1234

1234 is NOT a Fancy Number

67
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
5g)Create a module named “Lendi” and create functions add Student, remove Student, search Student.
Access the above module using import statement.

Aim:

To create a Python module named Lendi that provides functions to add, remove, and search students in a list
and access the module using the import statement.

Description:

 Python modules allow us to group reusable functions inside a file (.py).

 We define a module named Lendi.py, which contains:

o add_student(name): Adds a student to the list.

o remove_student(name): Removes a student if they exist.

o search_student(name): Checks if a student is present.

 The module will be accessed from another script using import.

Algorithm:

Step 1: Create the Module (Lendi.py) with above functions.

Step 2: Create Another Script (main.py) to Access the Module

Expected Output:

Student 'Alice' added successfully!

Student 'Bob' added successfully!

Student 'Charlie' added successfully!

Student 'Alice' is present in the list.

Student 'David' not found!

Student 'Bob' removed successfully!

Student 'Bob' not found!

68
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
5h)Write a python script using lambdas, to take input as String, and sort the string SS in
descending/ascending order according to their frequency of its occurrences of characters.(Eg.
S=&#39;missisippi&#39;, SS=ispm)

Aim:

To write a Python script using lambda functions to sort the characters of a string in ascending/descending
order based on their frequency of occurrence.

Description:

 Given a string S, we need to count the frequency of each character.

 We then sort the characters in S based on their frequency:

o Descending Order → Higher frequency first.

o Ascending Order → Lower frequency first.

 We use:

o Counter from collections to count occurrences.

o sorted() with a lambda function to sort based on frequency.

Algorithm:

1. Take input string S from the user.

2. Use Counter from collections to count occurrences of each character.

3. Sort the characters using sorted() with a lambda function:

o Descending Order → Sort by negative frequency (higher first).

o Ascending Order → Sort by positive frequency (lower first).

4. Print the sorted characters as SS.

Input:

Enter a string: mississippi

Expected Output:

Descending Order (SS): ispm

Ascending Order: mpis


69
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
5i)Python program to check whether a JSON string contains complex object or not.

Aim:

To write a Python program that checks whether a JSON string contains a complex object (i.e., nested
dictionaries or lists).

Description:

 A JSON string may contain:

o Simple Objects → {"name": "Alice", "age": 25}

o Complex Objects → {"person": {"name": "Alice", "age": 25}, "hobbies": ["reading", "sports"]}

 The program should parse the JSON string and determine if it contains nested structures like:

o Dictionaries inside dictionaries ({ "key": { "subkey": "value" } })

o Lists inside dictionaries ({ "key": [ "value1", "value2" ] })

Algorithm:

1. Import json module to handle JSON data.

2. Take JSON string input from the user.

3. Parse JSON using json.loads() to convert it into a Python dictionary.

4. Check for complexity:

o If any value in the dictionary is another dictionary or a list, it is a complex object.

5. Print whether the JSON is simple or complex.

Example Runs

Example 1: Simple JSON

Input:

{"name": "Alice", "age": 25}

Output:

The JSON string does not contain a complex object.

Example 2: Complex JSON (Nested Dictionary)


70
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Input:

{"person": {"name": "Alice", "age": 25}, "city": "New York"}

Output:

The JSON string contains a complex object.

Example 3: Complex JSON (List Inside JSON)

Input:

{"name": "Bob", "hobbies": ["reading", "gaming", "sports"]}

Output:

The JSON string contains a complex object.

Example 4: Invalid JSON Input

Input:

{name: Alice, age: 25}

Output:

Invalid JSON! Please check your input.

VIVA-VOCE QUSTIONS

1. What is a lambda function in Python, and how is it used in this program?


2. How does the Counter class from the collections module help in counting the frequency of characters in a
string?
3. Explain the sorting logic used to sort the string based on character frequency. Why is the negative
frequency used for descending order?
4. What would happen if you removed the lambda function and used a different method to sort the string?
5. How does the json.loads() function work, and what is its role in this program?
6. What is the purpose of the isinstance() function in checking whether a value is a dictionary or a list?
7. Explain how the program identifies whether the JSON string contains a complex object. What defines a
complex object?
8. What happens if the user enters an invalid JSON string? How is this error handled in the program?
9. What are some common issues that could lead to a json.JSONDecodeError, and how could the program
handle those issues more gracefully?
10. Can this program be modified to not just check for complex objects but also output the structure or depth
of nesting? How would you approach that?
71
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 6: Programs Permutations &amp; Combinations

6a)Write a python script to take input as number N, and find out the largest number L , that can be
formed with N. Eg. N=679, P={679,697,769,796,967,976}, L = 976

Aim:

To write a Python script that takes an input number N, generates all possible numbers that can be formed
using its digits, and finds the largest number (L) among them.

Description:

 Given a number N, extract its digits and generate all possible permutations.

 Convert each permutation back into an integer and find the maximum value (L).

 We use:

o itertools.permutations() to generate digit permutations.

o max() to determine the largest number.

Algorithm:

1. Take input N from the user.

2. Extract digits and generate all permutations of these digits.

3. Convert permutations into integers.

4. Find the maximum value (L) using max().

5. Print the largest number (L).

Example 1

Input:

Enter a number: 679

Largest number that can be formed: 976

Example 2

Input:

Enter a number: 4321

72
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Largest number that can be formed: 4321

Example 3

Input:

Enter a number: 123

Largest number that can be formed: 321

73
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
6b)Write a python script to take input as list, L and print output as largest number L and total
combinations C for given N digit number formed by the combination of L.(Eg. L=[1,2,1,4], N=3,
L=421,C=12).

Aim:

To write a Python script that takes a list of digits (L) as input and a number of digits (N) to form numbers,
then finds:

1. The largest number (L) that can be formed using N digits from the list.

2. The total number of unique combinations (C) that can be formed.

Description:

 Given a list of digits (L) and a number N, we need to generate all possible combinations of length N.

 Convert these combinations to numbers and find the maximum value (L).

 Count the total number of possible numbers (C).

 We use:

o itertools.permutations() to generate unique orderings.

o max() to determine the largest number.

Algorithm:

1. Take input: A list of digits L and an integer N (length of numbers to form).

2. Generate all possible permutations of length N from the list.

3. Convert permutations into integers.

4. Find the largest number from the generated values.

5. Count total unique numbers (C).

6. Print the largest number (L) and total combinations (C).

Example 1

Input:

Enter list of digits (space-separated): 1 2 1 4

Enter the number of digits (N): 3


74
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Largest number (L): 421

Total combinations (C): 12

Example 2

Input:

Enter list of digits (space-separated): 3 5 7 8

Enter the number of digits (N): 2

Largest number (L): 87

Total combinations (C): 12

Example 3

Input:

Enter list of digits (space-separated): 9 9 8 7

Enter the number of digits (N): 3

Largest number (L): 998

Total combinations (C): 24

75
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
6c)Write a python script to print Prime pairs within a given range of numbers. (Hint N=20, then (3,5)
(5,7) (11,13) (17,19) are prime pairs).

Aim:

To write a Python script that finds and prints prime pairs within a given range N.

Description:

 A prime number is a number that is only divisible by 1 and itself.

 A prime pair consists of two consecutive prime numbers whose difference is 2 (e.g., (3,5), (5,7)).

 We generate all prime numbers up to N, then check for prime pairs.

 We use:

o is_prime() function to check if a number is prime.

o for loop to find prime numbers and store them.

o List iteration to find prime pairs.

Algorithm:

1. Take input N from the user.

2. Define is_prime(n) function to check if a number is prime.

3. Find all prime numbers up to N and store them in a list.

4. Check for prime pairs by iterating through the prime list.

5. Print the prime pairs.

Example 1

Input:

Enter the range N: 20

Prime pairs: [(3, 5), (5, 7), (11, 13), (17, 19)]

Example 2

Enter the range N: 50

Prime pairs: [(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43)]
76
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
6d)By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the
sum of the even-valued terms. for this

Aim:

To write a Python program that calculates the sum of even Fibonacci numbers whose values do not exceed 4
million.

Description:

 The Fibonacci sequence is generated using the formula:

F(n)=F(n−1)+F(n−2)F(n) = F(n-1) + F(n-2)F(n)=F(n−1)+F(n−2)

where F(1) = 1 and F(2) = 2.

 We generate Fibonacci numbers ≤ 4,000,000.

 We sum only the even-valued Fibonacci numbers.

 We use:

o Loop-based approach to generate Fibonacci numbers.

o Conditional check for even numbers.

Algorithm:

1. Initialize first two Fibonacci numbers: a = 1, b = 2.

2. Initialize sum_even = 0 to store the sum of even Fibonacci numbers.

3. Use a while loop to generate Fibonacci numbers until they exceed 4 million.

4. If the current Fibonacci number is even, add it to sum_even.

5. Update a and b for the next Fibonacci number.

6. Print the final sum_even.

Output:

Sum of even Fibonacci numbers below 4 million: 4613732

77
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
VIVA-VOCE QUESTIONS:

1. What is the role of the itertools.permutations() function in this program, and how does it work?
2. How does the max() function help in finding the largest number from the generated permutations?
3. What is the importance of converting the permutations from a tuple to a string and then to an integer in
this program?
4. How does the program handle cases where the input number contains repeated digits? For example,
N=112?
5. Explain why the program uses int(''.join(p)) in the expression to convert each permutation into
an integer.
6. What will happen if the user enters a number with a single digit? For example, N=5.
7. How could you modify the program to exclude any leading zeros in the generated numbers?
8. How would you modify this program to not only find the largest number but also return the smallest
number that can be formed from the digits of N?
9. What happens if the input number contains non-numeric characters (e.g., N=abc)? How can you
handle such inputs in the program?
10. What is the time complexity of this program? How does the itertools.permutations() function
affect performance for large numbers?

78
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 7: Programs String & Regular Expressions

7a)Write a program to perform the given operations on a strings i) Creating the string ii) slicing the
string iii) Delete character in the string .

Aim:

To write a Python program that performs the following operations on strings:

1. Creating a string

2. Slicing the string

3. Deleting a character from the string

Description:

 Strings in Python are immutable sequences of characters.

 We can create a string using assignment (=).

 We can slice a string using indexing ([start:end]).

 Since strings are immutable, we cannot directly delete a character, but we can create a new string
without the unwanted character.

Algorithm:

1. Create a string and print it.

2. Slice the string using different slicing techniques and print results.

3. Delete a character from the string by reconstructing it without that character.

Output:

Original String: Hello, Python!

Sliced String (0 to 5): Hello

Sliced String (-6 to end): Python!

Sliced String (Alternate Characters): Hlo yhn!

String after deleting character at index 7: Hello, ython!

79
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
7b)Write a python script to take two string S1 and S2 and Check S1 and S2 are anagrams or not.

Aim:

To write a Python program that takes two strings S1 and S2 as input and checks whether they are anagrams.

Description:

 Two strings are anagrams if they contain the same characters with the same frequency, but their order
can be different.

 Example:

o "listen" and "silent" are anagrams.

o "hello" and "world" are not anagrams.

 We can check for anagrams by sorting both strings or by using frequency counting with dictionaries.

Algorithm:

1. Take two string inputs S1 and S2.

2. Convert both strings to lowercase to ensure case insensitivity.

3. Remove spaces (if needed).

4. Sort both strings and compare them.

5. If they are equal, print "Anagrams"; otherwise, print "Not Anagrams".

Input 1:

Enter first string: listen

Enter second string: silent

Output 1:

The strings are Anagrams.

Input 2:

Enter first string: hello

Enter second string: world

Output 2:
80
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
The strings are Not Anagrams.

81
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
7c)Write a python script to take two string S1 and S2 and Check S1 is Sub string of S2 or not.

Aim:

To write a Python program that takes two strings S1 and S2 as input and checks whether S1 is a substring of
S2.

Description:

 A substring is a sequence of characters that appears consecutively within another string.

 Example:

o "hello" is a substring of "hello world".

o "python" is not a substring of "java programming".

 In Python, we can check this using the in keyword or the find() method.

Algorithm:

1. Take two string inputs S1 and S2.

2. Use the in operator or the find() method to check if S1 exists within S2.

3. If found, print "S1 is a substring of S2"; otherwise, print "S1 is not a substring of S2".

Input 1:

Enter first string (S1): hello

Enter second string (S2): hello world

Output 1:

"hello" is a substring of "hello world".

Input 2:

Enter first string (S1): python

Enter second string (S2): java programming

Output 2:

"python" is NOT a substring of "java programming".

82
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
7d)Write a python script to take two string S1 and S2 and check S1 is palindrome or not .

Aim:

To write a Python program that takes a string S1 as input and checks whether it is a palindrome.

Description:

 A palindrome is a string that reads the same forward and backward.

 Example:

o "madam" is a palindrome.

o "hello" is not a palindrome.

 In Python, we can check this by reversing the string and comparing it with the original.

Algorithm:

1. Take a string input S1 from the user.

2. Convert the string to lowercase to ensure case insensitivity.

3. Reverse the string using slicing (S1[::-1]).

4. Compare the original and reversed strings:

o If they are equal, print "S1 is a palindrome"

o Otherwise, print "S1 is not a palindrome"

Input 1:

Enter a string (S1): madam

Output 1:

"madam" is a palindrome.

Input 2:

Enter a string (S1): hello

Output 2:

"hello" is NOT a palindrome.

83
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
7e)Write a Python program to reverse a given string using a for loop. Take the string as input from the
user.

Aim:

To write a Python program that takes a string as input and reverses it using a for loop.

Description:

 Reversing a string means arranging its characters in the opposite order.

 Example:

o "hello" → "olleh"

o "python" → "nohtyp"

 This can be done using a for loop by iterating over the string in reverse order and constructing a new
string.

Algorithm:

1. Take a string S1 as input from the user.

2. Initialize an empty string to store the reversed version.

3. Use a for loop to iterate through the string from the last character to the first.

4. Append each character to the new string.

5. Print the reversed string as output.

Input 1:

Enter a string: hello

Output 1:

Reversed string: olleh

Input 2:

Enter a string: Python

Output 2:

Reversed string: nohtyP

84
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
7f)Write a python script to take input as multi-line string and find the sum of all numbers in that string
using re module. (Eg. S=”he11o they are 40students in97 room of 4th line” , Sum= 152)

Aim:

To write a Python script that takes a multi-line string as input and finds the sum of all numbers in that string
using the re module.

Description:

 The re module (Regular Expressions) in Python helps in pattern matching and extracting numbers
from a string.

 We extract all digits from the input string, convert them into integers, and compute their sum.

 Example:

o Input: "he11o they are 40students in97 room of 4th line"

o Numbers Extracted: 11, 40, 97, 4

o Sum: 11 + 40 + 97 + 4 = 152

Algorithm:

1. Take a multi-line string as input from the user.

2. Use the re.findall() function with the pattern \d+ to extract all numbers.

3. Convert the extracted numbers into integers.

4. Compute the sum of all numbers.

5. Print the sum as output.

Input:

Enter a multi-line string (Press Enter twice to stop input):

he11o they are 40students

in97 room of 4th line

Output:

Sum of all numbers in the string: 152


85
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
7g)Using RegEx object check whether given phone number, email address and password is valid or not.

Aim:

To write a Python script that checks whether a given phone number, email address, and password are valid
using Regular Expressions (RegEx).

Description:

 Regular Expressions (RegEx) allow pattern matching for validation.

 The script will:

1. Validate a phone number (Assuming a format like Indian numbers +91-9876543210 or


9876543210).

2. Validate an email address (Standard email format like example@domain.com).

3. Validate a password (Should contain at least one uppercase letter, one lowercase letter, one
digit, one special character, and be at least 8 characters long).

Regular Expression Patterns:

 Phone Number: ^\+91-\d{10}$|^\d{10}$

o Starts with +91- followed by 10 digits OR just 10 digits.

 Email Address: ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$

o Ensures standard email format.

 Password: ^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$

o At least one uppercase, one lowercase, one digit, one special character, and 8+ characters.

Algorithm:

1. Take phone number, email, and password as input.

2. Define RegEx patterns for each validation.

3. Use re.match() to check if inputs match their respective patterns.

4. Display whether each input is valid or invalid.

Input 1:

Enter phone number: 9876543210


86
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Enter email address: test@example.com

Enter password: Test@1234

Output 1:

Validation Results:

Phone Number: Valid

Email Address: Valid

Password: Valid

Input 2 (Invalid Cases):

Enter phone number: 12345

Enter email address: test@com

Enter password: pass123

Output 2:

Validation Results:

Phone Number: Invalid

Email Address: Invalid

Password: Invalid

87
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
7h)Using date module, write a python script to take input as Date of birth (DOB) and current date(CD)
and print age of the person. for this

Aim:

To write a Python script that calculates a person’s age based on their Date of Birth (DOB) and the Current
Date (CD) using the datetime module.

Description:

 The datetime module provides tools for date and time operations.

 The script will:

1. Take DOB and CD as input (format: YYYY-MM-DD).

2. Convert input strings to date objects.

3. Calculate years, months, and days between DOB and CD.

4. Display the age of the person.

Algorithm:

1. Import the datetime module.

2. Take Date of Birth (DOB) and Current Date (CD) as input in YYYY-MM-DD format.

3. Convert the input strings into datetime objects.

4. Compute the difference in years, months, and days.

5. Print the exact age of the person.

Input 1:

Enter Date of Birth (YYYY-MM-DD): 2000-05-15

Enter Current Date (YYYY-MM-DD): 2025-03-22

Output 1:

Age: 24 years, 10 months, 7 days

Input 2:

Enter Date of Birth (YYYY-MM-DD): 1998-12-10

88
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Enter Current Date (YYYY-MM-DD): 2024-02-29

Output 2:

Age: 25 years, 2 months, 19 days

VIVA-VOCE QUESTIONS:

1. What is a string in Python, and how is it different from other data types?
2. How can we create a string in Python?
3. What is string slicing, and how does it work?
4. Explain the meaning of s[::2] in the slicing operation.
5. Why are strings immutable in Python?
6. If strings are immutable, how do we "delete" a character from a string?
7. What will happen if we try to assign a new character to a specific index in a string?
8. How can we remove multiple characters from a string?
9. What is the difference between s[:5] and s[0:5]?
10. Can we use negative indices for string slicing? Give an example.

89
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 8: Programs Lists &amp; Dictionary

8a)Write a program to perform the given operations on a list: i) Creating the list ii) slicing in the lists
iii) Adding Elements in List iv) Deleting the list elements.

Aim:

To write a Python program that performs the following operations on a list:

1. Creating a list

2. Slicing the list

3. Adding elements to the list

4. Deleting elements from the list

Description:

 Lists in Python are mutable, allowing modification after creation.

 The script demonstrates:

o Creating a list with elements.

o Slicing to extract sublists.

o Adding elements using append(), insert(), and extend().

o Deleting elements using remove(), pop(), and del.

Algorithm:

1. Create a list with sample elements.

2. Slice the list using different index ranges.

3. Add elements using append(), insert(), and extend().

4. Delete elements using remove(), pop(), and del.

5. Print results at each step.

Example Output:

Original List: [10, 20, 30, 40, 50, 60]

Sliced List (First 3 elements): [10, 20, 30]


90
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Sliced List (Last 3 elements): [40, 50, 60]

Sliced List (Skipping elements): [10, 30, 50]

List after append(70): [10, 20, 30, 40, 50, 60, 70]

List after insert(25 at index 2): [10, 20, 25, 30, 40, 50, 60, 70]

List after extend([80, 90]): [10, 20, 25, 30, 40, 50, 60, 70, 80, 90]

List after remove(40): [10, 20, 25, 30, 50, 60, 70, 80, 90]

List after pop(3) (removed 30): [10, 20, 25, 50, 60, 70, 80, 90]

List after deleting element at index 1: [10, 25, 50, 60, 70, 80, 90]

Final List: [10, 25, 50, 60, 70, 80, 90]

91
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
8b) Write a program to count the number of vowels in a string(No control flow allowed).

Aim:

To write a Python program that counts the number of vowels in a given string without using control flow
statements like if, for, or while.

Description:

 The program takes a string as input.

 We use list comprehension and the sum() function to count vowels.

 sum() automatically adds up occurrences of vowels without explicit loops or conditions.

Algorithm:

1. Take input as a string from the user.

2. Use list comprehension with the sum() function to count vowels.

3. Print the total number of vowels.

Example Output:

Enter a string: Hello World

Number of vowels in the string: 3

Enter a string: Python Programming

Number of vowels in the string: 5

92
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
8c)Write a program to check if a given key exists in a dictionary or not.

Aim:

To write a Python program that checks whether a specified key exists in a dictionary.

Description:

 The program takes a dictionary and a key as input.

 It uses the in operator to check if the key exists in the dictionary.

 If the key exists, it prints a success message; otherwise, it prints a failure message.

Algorithm:

1. Define a sample dictionary or take user input for the dictionary.

2. Take a key as input from the user.

3. Use the in operator to check if the key exists in the dictionary.

4. Print the result.

Example Output:

Enter the key to check: age

Key 'age' exists in the dictionary with value: 25

Enter the key to check: country

Key 'country' does not exist in the dictionary.

93
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
8d)Write a program to add a new key-value pair to an existing dictionary.

Aim:

To write a Python program that adds a new key-value pair to an existing dictionary.

Description:

 The program defines an initial dictionary.

 It takes a new key and value as input from the user.

 It updates the dictionary with the new key-value pair.

 Finally, it prints the updated dictionary.

Algorithm:

1. Define an initial dictionary with some key-value pairs.

2. Take user input for the new key and value.

3. Use dictionary assignment (dict[key] = value) to add the new pair.

4. Print the updated dictionary.

Example Output:

Enter the new key: country

Enter the new value: USA

Updated Dictionary: {'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}

94
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
8e)Write a program to take input as String S and print frequency of each character in S using List data
structure.

Aim:

To write a Python program that takes a string as input and prints the frequency of each character using a list
data structure.

Description:

 The program takes a string S as input from the user.

 It initializes an empty list to store character frequencies.

 It iterates through the string and records each character’s count.

 Finally, it prints the frequency of each character.

Algorithm:

1. Take input string S from the user.

2. Initialize an empty list to store character-frequency pairs.

3. Iterate through the string and store character frequencies in the list.

4. Print the frequency of each character in the string.

Example Output:

Enter a string: hello

Character Frequencies:

'h' : 1

'e' : 1

'l' : 2

'o' : 1

95
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
8f)Write a program to take input as String S contains characters and special symbols, reverse the
String S such that special symbols remains at same position. (Eg. S=”m@d#u” , Output=”u@d#m”).

Aim:

To write a Python program that reverses only the alphabetic characters in a given string while keeping special
symbols in the same position.

Description:

 The program takes S as input.

 It extracts the alphabetical characters and reverses them.

 It places them back in the original string while keeping special symbols in place.

Algorithm:

1. Take input string S from the user.

2. Extract only alphabetic characters and store them in a list.

3. Reverse the list of alphabetic characters.

4. Rebuild the string by replacing characters while keeping special symbols unchanged.

5. Print the final string as output.

Example Output:

Enter the string: m@d#u

Reversed String: u@d#m

96
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
8g)Write a python script to take input as String sentence S and print each word count using dictionary.

Aim:

To write a Python program that takes a sentence as input and prints the count of each word using a dictionary.

Description:

 The program takes a sentence (S) as input.

 It splits the sentence into words.

 It uses a dictionary to count the occurrences of each word.

 Finally, it prints the word frequencies.

Algorithm:

1. Take input string S from the user.

2. Split the string into words using split().

3. Initialize an empty dictionary to store word counts.

4. Iterate through words and update their counts in the dictionary.

5. Print the word frequency dictionary.

Example Output:

Enter a sentence: Python is easy and Python is fun

Word Count:

'python': 2

'is': 2

'easy': 1

'and': 1

'fun': 1

97
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
8h)Write a python script to implement Anonymous function.

Aim:

To write a Python script that demonstrates the use of anonymous (lambda) functions.

Description:

 Lambda functions are anonymous functions that have no name and are defined using the lambda
keyword.

 They can take multiple arguments but contain only a single expression.

 These functions are useful for short, one-time operations.

Algorithm:

1. Define a lambda function with the required operation.

2. Use the lambda function by passing inputs and getting the result.(ex: lambda x, y: x + y)

3. Print the output.

Example Output:

Addition: 8

Square of 4: 16

Number 7 is: Odd

Maximum of 10 and 20: 20

98
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
8i)Write a python script to implement map(), reduce() and filter() functions.

Aim:

To write a Python script that demonstrates the use of map(), filter(), and reduce() functions.

Description:

 map(function, iterable): Applies a function to each element of an iterable and returns the results.

 filter(function, iterable): Filters elements from an iterable based on a condition (returns only True
values).

 reduce(function, iterable): Reduces an iterable to a single value by applying a function cumulatively.

Algorithm:

1. Define a list of numbers.

2. Implement map() to apply a function to each element.(ex: squares of given list of numbers)

3. Implement filter() to filter specific elements.(ex: filtering even numners in list)

4. Implement reduce() to compute a single result.(ex: sum of list elements)

5. Print the results.

Example Output:

Squared Numbers: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Even Numbers: [2, 4, 6, 8, 10]

Sum of All Numbers: 55

VIVA-VOCE QUESTIONS:

1. What is the purpose of this program?

2. How does this program handle special characters in the string?

3. What is the role of the isalpha() function in this program?

4. Why do we store alphabetic characters in a list before reversing?

5. How does [::-1] work in Python?

6. What will be the output if the input is "a@b$c"?


99
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
7. Can this program handle numbers along with special characters?

8. How can we modify this program to ignore spaces while reversing the string?

9. What is the time complexity of this approach?

10. Can this problem be solved using recursion? If yes, how?

100
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 9: Programs OOPS.

9a)Write a Python program to create a person class. Include attributes like name, country and date of
birth. Implement a method to determine the person’s age.

Aim:

To create a Person class with attributes name, country, and date of birth, and implement a method to
determine the person's age.

Description:

 The Person class contains:

o Attributes: name, country, and date_of_birth.

o A method calculate_age() to determine the age of the person.

 The calculate_age() method subtracts the year of birth from the current year to determine the person's
age.

 The datetime module is used to get the current date.

Algorithm:

1. Import the datetime module.

2. Define a Person class with attributes: name, country, and date_of_birth.

3. Implement a method calculate_age():

o Extract the birth year from date_of_birth.

o Get the current year using datetime.today().year.

o Compute the age as current_year - birth_year.

4. Create an instance of the Person class.

5. Call the calculate_age() method and display the output.

Example Output:

Name: John Doe

Country: USA

Age: 29 years
101
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
9b)Write a Python program to create a calculator class. Include methods for basic arithmetic
operations.

Aim:

To create a Calculator class that performs basic arithmetic operations such as addition, subtraction,
multiplication, and division.

Description:

 The Calculator class includes the following methods:

o add(a, b): Returns the sum of a and b.

o subtract(a, b): Returns the difference of a and b.

o multiply(a, b): Returns the product of a and b.

o divide(a, b): Returns the division of a by b. (Handles division by zero exception)

 The user inputs two numbers and selects an operation.

 The appropriate method is called, and the result is displayed.

Algorithm:

1. Define a class Calculator.

2. Inside the class, define methods for:

o Addition

o Subtraction

o Multiplication

o Division (with error handling for zero division)

3. Create an object of the Calculator class.

4. Accept user input for two numbers and the desired operation.

5. Call the appropriate method and display the result.

Example Output:

Enter first number: 10

102
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Enter second number: 5

Select Operation:

1. Addition

2. Subtraction

3. Multiplication

4. Division

Enter choice (1/2/3/4): 3

Result: 50.0

103
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
9c)Write a Python program to create a class representing a shopping cart. Include methods for adding
and removing items, and calculating the total price.

Aim:

To create a ShoppingCart class that allows users to:

1. Add items to the cart.

2. Remove items from the cart.

3. Calculate the total price of the items in the cart.

Description:

 The ShoppingCart class will store items as a dictionary with item names as keys and a tuple of (price,
quantity) as values.

 Methods:

o add_item(name, price, quantity): Adds an item to the cart.

o remove_item(name): Removes an item from the cart.

o calculate_total(): Calculates the total price of all items in the cart.

o display_cart(): Displays the cart contents.

Algorithm:

1. Define a class ShoppingCart with an empty dictionary to store items.

2. Implement add_item() to add items with price and quantity.

3. Implement remove_item() to remove an item from the dictionary.

4. Implement calculate_total() to iterate through the cart and compute the total price.

5. Implement display_cart() to show items in the cart.

6. Create an instance of ShoppingCart and allow user interaction via input.

Example Output:

2 Apple(s) added to cart.

1 Milk(s) added to cart.

104
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1 Bread(s) added to cart.

Shopping Cart:

Apple - ₹30 x 2 = ₹60

Milk - ₹50 x 1 = ₹50

Bread - ₹40 x 1 = ₹40

Total Price: ₹150

Milk removed from cart.

Shopping Cart:

Apple - ₹30 x 2 = ₹60

Bread - ₹40 x 1 = ₹40

Total Price: ₹100

Final Total: 100

105
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
9d)Using Python OOPS, create a class, constructor, method, __str__ and __repr__ for Employee.

Aim:

To create an Employee class using Object-Oriented Programming (OOPs) in Python that includes:

1. A constructor (__init__) to initialize employee details.

2. A method to display employee information.

3. The __str__ method for user-friendly output.

4. The __repr__ method for developer debugging representation.

Description:

 The Employee class will have attributes like name, employee_id, department, and salary.

 The __init__ constructor initializes these attributes.

 A method (get_details) is used to display the employee’s details.

 The __str__ method returns a readable string representation of the object.

 The __repr__ method returns a more technical/debugging-friendly representation of the object.

Algorithm:

1. Define a class Employee.

2. Create a constructor __init__ to initialize attributes.

3. Define a method get_details() to print employee details.

4. Implement __str__ to return a formatted string for users.

5. Implement __repr__ to return an official string for debugging.

6. Create employee objects and demonstrate functionality.

Example Output:

Employee ID: 101, Name: John Doe, Department: IT, Salary: ₹75000

Employee: John Doe (101), Dept: IT, Salary: ₹75000

Employee('Alice Smith', 102, 'HR', 68000)

106
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
9e)Using Python OOPS, create a class, constructor, method, __str__ and __repr__ for Student

Aim:

To create a Student class using Object-Oriented Programming (OOPs) in Python that includes:

1. A constructor (__init__) to initialize student details.

2. A method to display student information.

3. The __str__ method for user-friendly output.

4. The __repr__ method for developer debugging representation.

Description:

 The Student class will have attributes like name, student_id, course, and marks.

 The __init__ constructor initializes these attributes.

 A method (get_details) is used to return the student’s details.

 The __str__ method returns a readable string representation of the object.

 The __repr__ method returns a more technical/debugging-friendly representation of the object.

Algorithm:

1. Define a class Student.

2. Create a constructor __init__ to initialize attributes.

3. Define a method get_details() to return student details.

4. Implement __str__ to return a formatted string for users.

5. Implement __repr__ to return an official string for debugging.

6. Create student objects and demonstrate functionality.

Example Output:

Student ID: 201, Name: Alice Johnson, Course: Computer Science, Marks: 89%

Student: Alice Johnson (201), Course: Computer Science, Marks: 89%

Student('Bob Smith', 202, 'Mathematics', 92)

107
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Viva-Voice Questions
1)What is a class in Python?

2)What is an object in Python?

3)How do you define a method in a Python class?

4)How do you access a class attribute inside a method?

5)In Python, what is the role of the @classmethod decorator?

6)n Python, what is the purpose of the super() function in a class?

7)How can you access a class-level attribute in Python?

8)How can you create a custom exception class in Python?

9)In Python, what is the purpose of the __iter__ method in a class?

10)Explain OOPS principles?

108
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 10: Programs on Exceptions.

10a)Write a python program to implement Exceptions hierarchy.

Aim:

To demonstrate the exception hierarchy in Python by creating a custom exception class and handling different
types of exceptions.

Description:

 Python has a built-in hierarchy of exceptions, starting from the base class BaseException, from which
Exception is derived.

 Various built-in exceptions like ValueError, TypeError, ZeroDivisionError, etc., are subclasses of
Exception.

 We will create a custom exception class that inherits from Exception and demonstrate handling
multiple exceptions using a try-except block.

Python Exception Hierarchy (Simplified)

Explanation of Exception Handling:

Exception Reason Handled By

109
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Exception Reason Handled By

except
ZeroDivisionError Division by zero (10/0)
ZeroDivisionError:

ValueError Converting "abc" to int except ValueError:

IndexError Accessing index 5 in a 3-element list except IndexError:

CustomError Raising a user-defined exception except CustomError:

Exception Catches any other unexpected errors except Exception as e:

finally Executes regardless of exception finally:

Algorithm:

1. Define a custom exception class (CustomError) by inheriting from Exception.

2. Create a function that triggers different exceptions based on input.

3. Use a try-except block to handle different exceptions.

4. Catch specific exceptions like ZeroDivisionError, ValueError, and the custom exception separately.

5. Catch all remaining exceptions using a generic except Exception: clause.

Case 1: Enter 1 (ZeroDivisionError)

Enter a number (1-4) to trigger an exception: 1

Error: Cannot divide by zero.

Execution completed.

Case 2: Enter 2 (ValueError)

Enter a number (1-4) to trigger an exception: 2

Error: Invalid value provided.

Execution completed.

Case 3: Enter 3 (IndexError)


110
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Enter a number (1-4) to trigger an exception: 3

Error: Index out of range.

Execution completed.

Case 4: Enter 4 (Custom Exception)

Enter a number (1-4) to trigger an exception: 4

Custom Exception Caught: Triggered a Custom Error

Execution completed.

Case 5: Enter 5 (No Exception)

Enter a number (1-4) to trigger an exception: 5

Result: No Exception Raised

Execution completed.

111
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
10b)Write a program to Catching Specific Exceptions in Python.

Aim:

To demonstrate how to catch specific exceptions in Python using try-except blocks.

Description:

 Python provides various built-in exceptions that can occur during program execution.

 Using try-except, we can handle specific exceptions instead of catching all exceptions.

 This helps in debugging and proper error handling for different cases.

Algorithm:

1. Use a try block to write code that may raise an exception.

2. Use except blocks to catch specific exceptions (ZeroDivisionError, ValueError, etc.).

3. If an exception is caught, print an appropriate message.

4. Use a general except Exception: block to catch any unexpected errors.

5. Use a finally block to execute cleanup code.

Example Outputs:

Case 1: Enter 10 and 0 (ZeroDivisionError)

Enter first number: 10

Enter second number: 0

Error: Division by zero is not allowed.

Program execution completed.

Case 2: Enter abc (ValueError)

Enter first number: abc

Error: Invalid input! Please enter numeric values.

Program execution completed.

Case 3: File not found (FileNotFoundError)

112
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Enter first number: 10

Enter second number: 2

Result of division: 5.0

Error: The file 'sample.txt' was not found.

Program execution completed.

Case 4: No Exception

(Assuming sample.txt exists with content)

Enter first number: 10

Enter second number: 2

Result of division: 5.0

File Content: Hello, this is a sample file.

Program execution completed.

113
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
10c)Python program to try with else clause.

Aim:

To demonstrate how to use the else clause with try-except blocks in Python.

Description:

 The else block executes only if no exception occurs inside the try block.

 This is useful when we want to execute code only if there are no errors.

 The finally block (optional) is executed regardless of whether an exception occurs or not.

Algorithm:

1. Use a try block to write code that may raise an exception.

2. Use specific except blocks to catch known exceptions (ZeroDivisionError, ValueError, etc.).

3. If no exception occurs, the else block executes.

4. The finally block executes regardless of exceptions (optional).

Example Outputs:

Case 1: No Exception (Valid Input)

Enter first number: 10

Enter second number: 2

Division successful! Result: 5.0

Execution completed.

Case 2: Division by Zero (ZeroDivisionError)

Enter first number: 10

Enter second number: 0

Error: Division by zero is not allowed.

Execution completed.

Case 3: Invalid Input (ValueError)

114
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Enter first number: abc

Error: Invalid input! Please enter numeric values.

Execution completed.

115
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
10d)Write a Python program to handle a Zero Division Error exception when dividing a number by
zero.

Aim:

To demonstrate how to handle the ZeroDivisionError exception when attempting to divide a number by zero.

Description:

 A ZeroDivisionError occurs when a number is divided by zero.

 We use a try-except block to catch the error and prevent program crashes.

 A user-friendly message is displayed instead of an unhandled error.

Algorithm:

1. Take two numbers as input from the user.

2. Use a try block to attempt the division operation.

3. If a ZeroDivisionError occurs, handle it in the except block.

4. Display an appropriate message if an error occurs.

5. If no error occurs, print the result.

6. Use a finally block (optional) to display a completion message.

Example Outputs:

Case 1: No Exception (Valid Input)

Enter the numerator: 10

Enter the denominator: 2

Result: 5.0

Execution completed.

Case 2: Division by Zero (ZeroDivisionError)

Enter the numerator: 10

Enter the denominator: 0

Error: Division by zero is not allowed.


116
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Execution completed.

117
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
10e)Create a user defined Exception named “FundsLessException” and raise the exception when there
are no enough funds in the bank account.

Aim:

To create a custom exception named FundsLessException and raise it when there are insufficient funds in a
bank account.

Description:

 A user-defined exception allows creating custom error handling for specific scenarios.

 Here, FundsLessException is created and raised when a withdrawal amount exceeds the account
balance.

 A BankAccount class is implemented to manage deposits and withdrawals safely.

Algorithm:

1. Define a custom exception FundsLessException by inheriting from Exception.

2. Implement a BankAccount class with:

o A constructor to initialize the balance.

o deposit() method to add funds.

o withdraw() method to withdraw funds.

3. In the withdraw() method:

o If the requested amount is greater than the balance, raise FundsLessException.

o Else, deduct the amount and update the balance.

4. Handle the exception in a try-except block.

Case 1: Sufficient Balance

Amount Deposited: ₹500. Updated Balance: ₹1500

Amount Withdrawn: ₹1200. Updated Balance: ₹300

Transaction Failed: Insufficient balance! Available: ₹300, Requested: ₹500

Bank transaction completed.

Case 2: Insufficient Balance on First Withdrawal


118
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Amount Deposited: ₹500. Updated Balance: ₹1500

Transaction Failed: Insufficient balance! Available: ₹1500, Requested: ₹2000

Bank transaction completed.

Viva-Voice Questions

1) What are the keywords used for exception handling?

2) What is the difference between exception and an error?

3) What are the types of exceptions?

4) How to raise the user-defined exceptions?

5) What is the purpose of the finally block in exception handling?

6) What is the purpose of the else block in exception handling?

7) How can you catch multiple exceptions in a single except block?

8) What is the purpose of the assert statement in Python exception handling?

9) How can you handle exceptions globally in Python?

10) How can you re-raise an exception in Python?

119
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 11: Programs Data Analysis

11a)Python Program to demonstrate NumPy arrays creation using array()function.

Aim:

To create and demonstrate different types of NumPy arrays using the array() function.

Description:

 NumPy (Numerical Python) is a library used for efficient numerical computations in Python.

 The array() function in NumPy creates an array from Python lists or tuples.

 It supports 1D, 2D, and multi-dimensional arrays.

Algorithm:

1. Import NumPy as np.

2. Create arrays using np.array() for:

o 1D Array (Single-dimensional)

o 2D Array (Matrix)

o 3D Array (Tensor-like structure)

3. Print the created arrays with their data types.

4. Verify the array properties, such as shape and dimensions.

Example Output:

1D Array:

[10 20 30 40 50]

2D Array (Matrix):

[[1 2 3]

[4 5 6]

120
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
[7 8 9]]

3D Array:

[[[1 2]

[3 4]]

[[5 6]

[7 8]]]

Properties of Created Arrays:

1D Array - Shape: (5,), Dimensions: 1

2D Array - Shape: (3, 3), Dimensions: 2

3D Array - Shape: (2, 2, 2), Dimensions: 3

121
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
11b)Python script to load data sets.

Aim:

To load different types of datasets in Python using popular libraries such as NumPy, Pandas, and Scikit-
learn.

Description:

 Data loading is a crucial step in data analysis and machine learning.

 Python provides various libraries to handle structured and unstructured data formats.

 We will demonstrate loading datasets using:

1. NumPy (.txt or .csv files)

2. Pandas (.csv, .xlsx, .json)

3. Scikit-learn (built-in datasets like Iris and Digits)

Algorithm:

1. Import required libraries (numpy, pandas, sklearn.datasets).

2. Load data using NumPy (loadtxt() for .txt and .csv).

3. Load data using Pandas (read_csv(), read_excel(), read_json()).

4. Load built-in datasets from Scikit-learn (datasets.load_iris(), datasets.load_digits()).

5. Display the dataset information (head, shape, and description).

Example Output (If data.csv exists):

NumPy Data Loaded:

[[ 1. 50. 3.5]

[ 2. 60. 4.2]

[ 3. 70. 5.1]

[ 4. 80. 6.3]

[ 5. 90. 7.8]]

122
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Pandas Data (First 5 Rows):

ID Value Score

0 1 50 3.5

1 2 60 4.2

2 3 70 5.1

3 4 80 6.3

4 5 90 7.8

Iris Dataset (First 5 Rows):

sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)

0 5.1 3.5 1.4 0.2

1 4.9 3.0 1.4 0.2

2 4.7 3.2 1.3 0.2

3 4.6 3.1 1.5 0.2

4 5.0 3.6 1.4 0.2

123
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
11c)Write a python script to create a data frame.

Aim:

To create a DataFrame in Python using the Pandas library.

Description:

 A DataFrame is a two-dimensional labeled data structure in Pandas similar to an Excel sheet or SQL
table.

 It consists of rows and columns, where each column can have different data types.

 DataFrames can be created from lists, dictionaries, NumPy arrays, or external files like CSV and
Excel.

Algorithm:

1. Import the Pandas library.

2. Create a DataFrame using different approaches:

o Using a dictionary.

o Using a list of lists.

o Using a NumPy array.

3. Print the DataFrame and its properties like shape, columns, and data types.

Example Output:

DataFrame from Dictionary:

ID Name Age Score

0 101 Alice 25 85.5

1 102 Bob 30 90.2

2 103 Charlie 22 88.3

3 104 David 35 92.5

DataFrame from List of Lists:

124
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
ID Name Age Score

0 101 Alice 25 85.5

1 102 Bob 30 90.2

2 103 Charlie 22 88.3

3 104 David 35 92.5

DataFrame from NumPy Array:

ID Name Age Score

0 101 Alice 25 85.5

1 102 Bob 30 90.2

2 103 Charlie 22 88.3

3 104 David 35 92.5

DataFrame Information:

<class 'pandas.core.frame.DataFrame'>

RangeIndex: 4 entries, 0 to 3

Data columns (total 4 columns):

# Column Non-Null Count Dtype

--- ------ -------------- -----

0 ID 4 non-null int64

1 Name 4 non-null object

2 Age 4 non-null int64

3 Score 4 non-null float64

dtypes: float64(1), int64(2), object(1)

125
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
memory usage: 260.0+ bytes

None

Shape of DataFrame: (4, 4)

Column Names: ['ID', 'Name', 'Age', 'Score']

126
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
11d)Python program to demonstrate use of ndim, shape,size,dtype.

Aim:

To explore and demonstrate the usage of ndim, shape, size, and dtype properties in NumPy arrays.

Description of Attributes:

1. ndim → Returns the number of dimensions (axes) of the array.

2. shape → Returns a tuple representing the shape (dimensions) of the array.

3. size → Returns the total number of elements in the array.

4. dtype → Returns the data type of elements stored in the array.

Algorithm:

1. Import the NumPy library.

2. Create different types of NumPy arrays (1D, 2D, and 3D).

3. Display the properties ndim, shape, size, and dtype for each array.

Example Output:

1D Array:

[1 2 3 4 5]

Number of Dimensions (ndim): 1

Shape (rows, columns): (5,)

Total Elements (size): 5

Data Type (dtype): int64

--------------------------------------------------

2D Array:

[[1 2 3]

[4 5 6]]

Number of Dimensions (ndim): 2

127
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Shape (rows, columns): (2, 3)

Total Elements (size): 6

Data Type (dtype): int64

--------------------------------------------------

3D Array:

[[[1 2]

[3 4]]

[[5 6]

[7 8]]]

Number of Dimensions (ndim): 3

Shape (depth, rows, columns): (2, 2, 2)

Total Elements (size): 8

Data Type (dtype): int64

128
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
11e)Using NumPy, implement different matrix operations in python.

Aim:

To perform various matrix operations such as addition, subtraction, multiplication, transpose, and determinant
using NumPy in Python.

Description of Operations:

1. Matrix Addition (A + B) → Adds corresponding elements of two matrices.

2. Matrix Subtraction (A - B) → Subtracts corresponding elements of two matrices.

3. Matrix Multiplication (A * B or np.dot(A, B)) → Computes the dot product of two matrices.

4. Element-wise Multiplication (A * B) → Multiplies corresponding elements.

5. Matrix Transpose (A.T) → Swaps rows with columns.

6. Matrix Determinant (np.linalg.det(A)) → Computes the determinant of a square matrix.

Algorithm:

1. Import the NumPy library.

2. Create two matrices A and B using np.array().

3. Perform matrix addition, subtraction, and multiplication.

4. Compute transpose and determinant of a matrix.

5. Display the results.

Example Output:

Matrix A:

[[1 2]

[3 4]]

Matrix B:

[[5 6]

[7 8]]

--------------------------------------------------
129
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Matrix Addition (A + B):

[[ 6 8]

[10 12]]

Matrix Subtraction (A - B):

[[-4 -4]

[-4 -4]]

Matrix Multiplication (A * B):

[[19 22]

[43 50]]

Element-wise Multiplication (A * B):

[[ 5 12]

[21 32]]

Transpose of Matrix A:

[[1 3]

[2 4]]

Determinant of Matrix A: -2.0

130
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
11f)Using pandas, read the data from any text files.

Aim:

To read data from a text file using the pandas library in Python.

Description:

 Pandas provides functions like pd.read_csv() and pd.read_table() to read text files efficiently.

 We can specify delimiters such as commas (,), tabs (\t), or spaces.

 We can also handle missing values and format the data accordingly.

Algorithm:

1. Import pandas library.

2. Read the text file using pd.read_csv().

3. Display the first few rows of the dataset using .head().

4. Handle missing values if necessary.

5. Print the data for verification.

Example Input File (data.txt):

Name Age Score

Alice 24 85

Bob 27 90

Charlie 22 88

David 25 78

Eve 23 95

Example Output:

First 5 rows of the dataset:

Name Age Score

0 Alice 24 85

131
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1 Bob 27 90

2 Charlie 22 88

3 David 25 78

4 Eve 23 95

Dataset Information:

<class 'pandas.core.frame.DataFrame'>

RangeIndex: 5 entries, 0 to 4

Data columns (total 3 columns):

# Column Non-Null Count Dtype

--- ------ -------------- -----

0 Name 5 non-null object

1 Age 5 non-null int64

2 Score 5 non-null int64

dtypes: int64(2), object(1)

memory usage: 248.0+ bytes

Statistical Summary:

Age Score

count 5.00000 5.00000

mean 24.20000 87.20000

std 1.92354 6.83374

min 22.00000 78.00000

max 27.00000 95.00000

132
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
11g)Python program to find min, max, sum, cumulative sum of array.

Aim:

To demonstrate array operations such as finding the minimum, maximum, sum, and cumulative sum using
the NumPy library in Python.

Description:

 NumPy is a powerful library used for numerical computations.

 We will create a NumPy array and use built-in functions:

o np.min() → Finds the minimum value.

o np.max() → Finds the maximum value.

o np.sum() → Computes the sum of all elements.

o np.cumsum() → Computes the cumulative sum.

Algorithm:

1. Import NumPy library.

2. Create an array using np.array().

3. Find the minimum value using np.min().

4. Find the maximum value using np.max().

5. Compute the sum of all elements using np.sum().

6. Compute the cumulative sum using np.cumsum().

7. Display the results.

Example Output:

Original Array: [10 20 30 40 50]

Minimum Value: 10

Maximum Value: 50

Sum of Elements: 150

Cumulative Sum: [ 10 30 60 100 150]


133
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
11h)Create a dictionary with at least five keys and each key represent value as a list where this list contains at
least ten values and convert this dictionary as a pandas data frame and explore the data through the data frame
as follows:Apply head() function to the pandas data frame for this

Aim:

To create a dictionary where each key represents a list of values, convert it into a Pandas DataFrame, and
explore the data using the head() function.

Description:

 Dictionaries in Python store key-value pairs. Here, each key stores a list of 10 values.

 Pandas DataFrame is used to store data in tabular format.

 head() function in Pandas is used to display the first few rows of the dataset.

Algorithm:

1. Import Pandas library.

2. Create a dictionary with 5 keys, each containing a list of 10 values.

3. Convert the dictionary into a Pandas DataFrame using pd.DataFrame().

4. Apply the head() function to view the first 5 rows.

5. Display the output.

Example Output:

First 5 Rows of DataFrame:

Student_ID Name Age Marks City

0 101 Alice 20 85 NY

1 102 Bob 22 78 LA

2 103 Charlie 21 90 SF

3 104 David 23 88 TX

4 105 Emma 22 76 FL

134
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
11i)Perform various data selection operations on Data Frame

Aim:

To demonstrate various data selection operations on a Pandas DataFrame, including:

 Selecting specific columns

 Selecting specific rows

 Using conditional selection

 Using loc[] and iloc[]

Description:

 Pandas DataFrame allows easy data selection using indexing and slicing techniques.

 loc[] is label-based indexing, and iloc[] is position-based indexing.

 We can apply conditional filtering to select specific rows based on a condition.

Algorithm:

1. Import Pandas.

2. Create a dictionary with sample data.

3. Convert it into a Pandas DataFrame.

4. Perform the following data selection operations:

o Selecting a single column

o Selecting multiple columns

o Selecting specific rows

o Using loc[] (label-based selection)

o Using iloc[] (position-based selection)

o Using conditions to filter rows

5. Display the results.

Example Output:

135
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Selecting 'Name' column:

0 Alice

1 Bob

2 Charlie

3 David

4 Emma

5 Frank

Name: Name, dtype: object

Selecting 'Name' and 'Marks' columns:

Name Marks

0 Alice 85

1 Bob 78

2 Charlie 90

3 David 88

4 Emma 76

5 Frank 95

Selecting first 3 rows using iloc:

Student_ID Name Age Marks City

0 101 Alice 20 85 NY

1 102 Bob 22 78 LA

2 103 Charlie 21 90 SF

136
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Selecting rows where Student_ID is 104:

Student_ID Name Age Marks City

3 104 David 23 88 TX

Selecting students with Marks > 80:

Student_ID Name Age Marks City

0 101 Alice 20 85 NY

2 103 Charlie 21 90 SF

3 104 David 23 88 TX

5 106 Frank 24 95 DC

Selecting row index 2, 'Marks' column value:

90

Selecting 3rd row and 2nd column using iloc:

Charlie

Viva-Voice questions
1) What is NumPy, and what is it used for?

2 )What is the difference between a Python list and a NumPy array?

3) How do you access elements in a NumPy array?

4) What is Pandas, and what is it used for?

5) What is the difference between a Pandas Series and a DataFrame?

6) How do you read data from a CSV file into a Pandas DataFrame?

7)How do you reshape a NumPy array?

137
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
8) What does ndim represent in a Pandas DataFrame?

9) How do you sort a Pandas DataFrame?

10) How do you create a 1D and 2D NumPy array

138
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 12: Programs Plotting

12a)Create a line plot for a list of values over a period of time. Label the x-axis as &quot;Time&quot;
and the y-axis as &quot;Value&quot;.

Aim:

To create a line plot that visualizes the change in a list of values over a period of time. The x-axis will
represent time, and the y-axis will represent the corresponding values. The plot will include labels for the axes
for better understanding.

Description:

A line plot is used to show trends over a period of time. It connects data points with lines, making it useful for
visualizing the relationship between time (x-axis) and a continuous variable (y-axis). This type of plot is
commonly used in time-series analysis, where the dataset represents changes or trends over time.

Algorithm:

1. Step 1: Gather the dataset with time points and corresponding values.

2. Step 2: Plot the values against the time points using a line plot.

3. Step 3: Label the x-axis as "Time" and the y-axis as "Value".

4. Step 4: Add a title to the plot to provide context.

5. Step 5: Display the line plot.

Input:

 A dataset consisting of time points and their corresponding values. Example:

 time = [1, 2, 3, 4, 5, 6, 7, 8, 9] # Time points

 values = [3, 4, 5, 6, 7, 8, 7, 6, 5] # Values corresponding to each time point

Output:

 A line plot with time on the x-axis and values on the y-axis, showing how the values change over time.

139
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
12b)Create a bar chart that shows the frequency of categories in a dataset. Use different colors for each
bar.

Aim:

To create a bar chart that shows the frequency of different categories in a dataset. Each bar will represent a
category, and the bars will be displayed in different colors for better visualization.

Description:

A bar chart is a graphical representation used to show the frequency or count of categories in a dataset. Each
bar in the chart corresponds to a category, and its height represents the frequency of that category.
Customizing the colors of the bars enhances the visual appeal and helps in distinguishing between categories.

Algorithm:

1. Step 1: Gather the dataset, which includes categorical data and corresponding frequency counts.

2. Step 2: Plot the bar chart with each category on the x-axis and its frequency on the y-axis.

3. Step 3: Customize the colors of the bars to make the chart visually appealing.

4. Step 4: Add titles and labels for better understanding.

5. Step 5: Display the bar chart.

Input:

 A dataset consisting of categories and their corresponding frequencies. Example:

 categories = ['Category A', 'Category B', 'Category C', 'Category D']

 frequencies = [30, 50, 40, 60]

Output:

 A bar chart where the x-axis represents categories, the y-axis represents the frequency of each
category, and the bars are displayed in different colors.

140
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
12c)Create a histogram to visualize the distribution of a numerical dataset. Customize the number of
bins and add a title.

Aim:

To create a histogram to visualize the distribution of a numerical dataset. The histogram will display the
frequency of data within specified intervals (bins), and customization will include adjusting the number of
bins and adding a title to the chart.

Description:

A histogram is a graphical representation that organizes a dataset into bins (intervals) and shows the frequency
or count of data points that fall into each bin. It is useful for visualizing the distribution of a numerical dataset
and identifying patterns such as skewness, outliers, or the overall shape of the data.

Algorithm:

1. Step 1: Gather the numerical dataset.

2. Step 2: Define the number of bins or intervals to categorize the data.

3. Step 3: Plot the histogram using the data and chosen number of bins.

4. Step 4: Customize the histogram (e.g., add a title and labels).

5. Step 5: Display the histogram.

Input:

 A numerical dataset (e.g., a list or array of values). Example:

 data = [12, 15, 14, 18, 19, 13, 17, 16, 15, 12, 14, 19, 20, 18, 16]

Output:

 A histogram that shows the distribution of the data with customized bin sizes, and includes a title for
the plot.

141
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
12d)Create a scatter plot to show the relationship between two numerical variables. Add a trend line to
the scatter plot.

Aim:

To create a scatter plot that shows the relationship between two numerical variables and add a trend line to
visualize the correlation between them.

Description:

A scatter plot is used to display the relationship between two numerical variables. Each point in the plot
represents a pair of values from the dataset. Adding a trend line (usually a linear regression line) helps in
visualizing the overall pattern or relationship between the two variables.

Algorithm:

1. Step 1: Gather the dataset with two numerical variables (x and y).

2. Step 2: Plot the scatter plot using the x and y values.

3. Step 3: Calculate the best-fit line (trend line) using a linear regression model or other fitting methods.

4. Step 4: Plot the trend line over the scatter plot to visualize the relationship.

5. Step 5: Display the plot with labeled axes and title.

Input:

 A dataset containing two numerical variables: x and y. Example:

 x = [1, 2, 3, 4, 5, 6, 7, 8, 9]

 y = [3, 4, 2, 4, 5, 6, 7, 8, 9]

Output:

 A scatter plot showing the relationship between the two variables, with a trend line fitted to the data.

142
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
12e) Create a pie chart to show the proportion of different categories in a dataset. Add labels and
percentages to each slice.

Aim:

To create a pie chart that shows the proportion of different categories in a given dataset, and display the labels
and percentages on each slice of the pie chart.

Description:

A pie chart is a circular statistical graphic that is divided into slices to illustrate numerical proportions. Each
slice represents a category, and the size of each slice is proportional to the value of that category. Adding
labels and percentages makes it easier to understand the distribution of data.

Algorithm:

1. Step 1: Gather the dataset containing the different categories and their corresponding values.

2. Step 2: Calculate the percentage for each category.


Percentage of category=(Value of categoryTotal sum of all values)×100\text{Percentage of category}
= \left( \frac{\text{Value of category}}{\text{Total sum of all values}} \right) \times 100

3. Step 3: Create a pie chart with the categories as slices.

4. Step 4: Add labels to each slice showing the category name.

5. Step 5: Add percentages to each slice showing the proportion of the category relative to the total.

6. Step 6: Display the pie chart.

Input:

 A dataset containing categories and their corresponding values. Example:

 categories = ['Category A', 'Category B', 'Category C', 'Category D']

 values = [30, 40, 20, 10]

Output:

 A pie chart displaying the distribution of categories and their respective percentages. Example:

o Category A: 30%

o Category B: 40%

o Category C: 20%
143
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
o Category D: 10%

Viva-Voice Questions

1) What does a line plot show?

2) What is the impact of adding markers to a line plot?

3) What is a bar chart used for?

4) What is the difference between a vertical bar chart and a horizontal bar chart in terms of readability and
usage?

5) Why is it important to use different colors for bars in a bar chart, and how does it improve data
comprehension?

6) What does a histogram display?

7) How do you decide the number of bins to use when creating a histogram?

8) What is the purpose of a trend line in a scatter plot?

9) How do you interpret the size of each slice in a pie chart?

10) How does histogram differ from a bar chart?

144
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy