Python STUDENT Manual
Python STUDENT Manual
(C206)
(STUDENT copy)
II B.TECH –I SEM
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
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
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
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.
***
* *
** * *
* *
* *
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
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
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.
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:
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.
Interactive Mode:
Script Mode:
print("Hello, World!")
a=5
b = 10
sum = a + b
print("Sum:", sum)
Hello, World!
>>> a = 5
>>> b = 10
>>> a + b
15
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.
This experiment demonstrates reading a value from the user and printing it.
Algorithm:
4. Repeat the process for different types of inputs (string, integer, float).
Input:
Name: John
Age: 25
Expected Output:
3
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1c)Write a Python Program to Convert Celsius To Fahrenheit
Aim:
Description:
This experiment demonstrates how to read a Celsius value from the user and convert it to
Fahrenheit using a mathematical formula.
Algorithm:
Input:
Expected Output:
4
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1d) Write a Python program to compute area of triangle.
Aim:
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().
Input:
Expected Output:
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:
Description:
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:
Input:
Expected Output:
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.
Algorithm:
3. Convert the input values from string to floating-point numbers using float().
Input:
Enter x1: 3
Enter y1: 4
Enter x2: 7
Enter y2: 1
Expected Output:
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:
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().
Input:
Expected Output:
After swapping:
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:
By multiplying these values together, we can determine the total number of seconds in one day.
Algorithm:
Input:
Expected Output:
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:
This experiment takes input from the user and demonstrates various conversion functions.
Algorithm:
Input Example:
Enter a number: 5
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
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)
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:
3. Assignment Operators (=, +=, -=, *=, /=, %=, **=, //=)
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("a == b:", a == b)
print("a != b:", a != b)
# 3. Assignment Operators
print("\nAssignment Operators:")
x = a # Assign
x += b # x = x + b
x -= b
x *= b
13
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
print("x after *= b:", x)
x /= b
# 4. Logical Operators
print("\nLogical Operators:")
# 5. Bitwise Operators
print("\nBitwise Operators:")
# 6. Membership Operators
print("\nMembership Operators:")
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
Expected Output:
Arithmetic Operators:
Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Floor Division: 2
Modulus: 0
Exponentiation: 100000
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:
Bitwise Operators:
a | b (Bitwise OR): 15
a ^ b (Bitwise XOR): 15
Membership Operators:
16
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Is 10 in list1? True
Identity Operators:
x is z: True
x is y: False
x == y: True
x is not y: True
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:
Python's built-in max() function can also be used to simplify the process.
Algorithm:
o if num1 > num2 and num1 > num3, then num1 is the largest.
o elif num2 > num1 and num2 > num3, then num2 is the largest.
Input Example:
Expected Output:
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:
Algorithm:
Input Example 1:
Expected Output 1:
Input Example 2:
Expected Output 2:
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
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:
x^2 + bx + c = 0
Algorithm:
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:
Enter coefficient a: 1
Enter coefficient b: -4
Enter coefficient c: 4
Expected Output:
Enter coefficient a: 1
Enter coefficient b: 2
Enter coefficient c: 5
Expected Output:
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.
Algorithm:
Input Example:
Expected Output:
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:
Algorithm:
Expected Output:
Expected Output:
Aim:
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.
2. Initialize factorial = 1.
Input Example 1:
Enter a number: 5
Expected Output:
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 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:
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:
≥ 90 A+
80 - 89 A
70 - 79 B
60 - 69 C
50 - 59 D
< 50 Fail
Algorithm:
Input Example:
Expected Output:
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
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:
25 - 59 Working Citizen
16 - 24 College Student
4 - 15 School Kid
Algorithm:
Expected Output:
Expected Output:
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:
2. Initialize reverse = 0.
Input Example 1:
Expected Output:
Expected Output:
31
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Reversed Number: -6789
5. How can you make decisions using the try, except block in Python?
32
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 3: Programs on Loops(for ,while)
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
Input Example:
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:
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:
3. Multiply N by the loop variable and print the result in the format:
N × i = result
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:
0, 1, 1, 2, 3, 5, 8
Algorithm:
first = 0, second = 1
first = second
second = next
Input Example:
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,
For example:
5! = 5 × 4 × 3 × 2 × 1 = 120
3! = 3 × 2 × 1 = 6
1! = 1
0! = 1 (by definition)
Algorithm:
2. Initialize factorial = 1.
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:
The program takes an integer N from the user and prints the first N multiples of 5.
Algorithm:
o Increment count by 1.
o Increase num by 5.
Input Example:
Expected Output:
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:
For example:
If N = 5, then
S=1+2+3+4+5=15
If N = 10, then
S=1+2+...+10=55
Algorithm:
2. Initialize sum = 0.
Input Example:
Expected Output:
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:
For example:
6 = 2 × 3 → Pronic
12 = 3 × 4 → Pronic
20 = 4 × 5 → Pronic
110 = 10 × 11 → Pronic
Algorithm:
2. Initialize k = 0.
o If k * (k + 1) > N, break the loop (since numbers beyond this won't work).
Input Example 1:
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:
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:
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:
2. Define a list of available notes: [2000, 500, 200, 100, 50, 20, 10].
3. Initialize total_notes = 0.
Input Example:
Expected Output:
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:
Algorithm:
3. Initialize sum_digits = 0.
o Convert it to an integer.
Input Example 1:
Expected Output 1:
Input Example 2:
Enter an integer: 80
Expected Output 2:
7. How do you use a for loop to iterate over a list? How can you loop through a dictionary?
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:
Algorithm:
47
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
o Add corresponding elements and store in the result 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):
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
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.
3. Inside the loop, use another for loop to print numbers from 1 to the current row number.
Input:
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:
The row number determines both the number of elements and their values.
Example breakdown:
52
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
The outer loop controls the number of rows.
Algorithm:
3. Inside the loop, use another for loop to print the row number i times.
Input:
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="LENDI", 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:
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.
Algorithm:
Input:
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:
Description:
The third row has all *, forming the horizontal bar of "A".
The pattern follows a fixed width where spaces are used for alignment.
Algorithm:
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 (" "):
4. Print a new line (print()) after each row to move to the next line.
Expected Output:
57
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 5: Programs on Modules & Functions
Aim:
To write a Python program that defines a function capable of returning multiple values.
Description:
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:
Input:
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:
4. Variable-Length Arguments (*args and **kwargs) – Used when the number of arguments is unknown.
Algorithm:
Expected Output:
59
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Example 2: Using only required and default arguments
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:
Description:
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:
Algorithm:
total=price×quantity+(price×quantity×tax)
Expected Output:
61
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Example 2: Custom quantity, default tax
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:
Description:
Python provides file handling functions such as open(), write(), and close() to work with files.
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:
Expected Output:
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.
Algorithm:
o add(a, b) → Returns a + b.
o sub(a, b) → Returns a - b.
o mul(a, b) → Returns a * b.
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
We use recursion to repeatedly calculate the sum of digits until a single digit remains.
Algorithm:
o If n is a single-digit, return n.
Expected Output:
66
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Example 1:
Example 2:
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:
Algorithm:
Expected Output:
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='missisippi', 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:
We use:
Algorithm:
Input:
Expected Output:
Aim:
To write a Python program that checks whether a JSON string contains a complex object (i.e., nested
dictionaries or lists).
Description:
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:
Algorithm:
Example Runs
Input:
Output:
Output:
Input:
Output:
Input:
Output:
VIVA-VOCE QUSTIONS
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:
Algorithm:
Example 1
Input:
Example 2
Input:
72
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Largest number that can be formed: 4321
Example 3
Input:
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.
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).
We use:
Algorithm:
Example 1
Input:
Example 2
Input:
Example 3
Input:
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 pair consists of two consecutive prime numbers whose difference is 2 (e.g., (3,5), (5,7)).
We use:
Algorithm:
Example 1
Input:
Prime pairs: [(3, 5), (5, 7), (11, 13), (17, 19)]
Example 2
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:
We use:
Algorithm:
3. Use a while loop to generate Fibonacci numbers until they exceed 4 million.
Output:
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:
1. Creating a string
Description:
Since strings are immutable, we cannot directly delete a character, but we can create a new string
without the unwanted character.
Algorithm:
2. Slice the string using different slicing techniques and print results.
Output:
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:
We can check for anagrams by sorting both strings or by using frequency counting with dictionaries.
Algorithm:
Input 1:
Output 1:
Input 2:
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:
Example:
In Python, we can check this using the in keyword or the find() method.
Algorithm:
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:
Output 1:
Input 2:
Output 2:
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:
Example:
o "madam" is a palindrome.
In Python, we can check this by reversing the string and comparing it with the original.
Algorithm:
Input 1:
Output 1:
"madam" is a palindrome.
Input 2:
Output 2:
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:
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:
3. Use a for loop to iterate through the string from the last character to the first.
Input 1:
Output 1:
Input 2:
Output 2:
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 Sum: 11 + 40 + 97 + 4 = 152
Algorithm:
2. Use the re.findall() function with the pattern \d+ to extract all numbers.
Input:
Output:
Aim:
To write a Python script that checks whether a given phone number, email address, and password are valid
using Regular Expressions (RegEx).
Description:
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).
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:
Input 1:
Output 1:
Validation Results:
Password: Valid
Output 2:
Validation Results:
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.
Algorithm:
2. Take Date of Birth (DOB) and Current Date (CD) as input in YYYY-MM-DD format.
Input 1:
Output 1:
Input 2:
88
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Enter Current Date (YYYY-MM-DD): 2024-02-29
Output 2:
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 & 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:
1. Creating a list
Description:
Algorithm:
Example Output:
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]
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:
Algorithm:
Example Output:
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:
If the key exists, it prints a success message; otherwise, it prints a failure message.
Algorithm:
Example Output:
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:
Algorithm:
Example Output:
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:
Algorithm:
3. Iterate through the string and store character frequencies in the list.
Example Output:
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:
It places them back in the original string while keeping special symbols in place.
Algorithm:
4. Rebuild the string by replacing characters while keeping special symbols unchanged.
Example Output:
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:
Algorithm:
Example Output:
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.
Algorithm:
2. Use the lambda function by passing inputs and getting the result.(ex: lambda x, y: x + y)
Example Output:
Addition: 8
Square of 4: 16
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).
Algorithm:
2. Implement map() to apply a function to each element.(ex: squares of given list of numbers)
Example Output:
Squared Numbers: [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
VIVA-VOCE QUESTIONS:
8. How can we modify this program to ignore spaces while reversing the string?
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 calculate_age() method subtracts the year of birth from the current year to determine the person's
age.
Algorithm:
Example Output:
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:
Algorithm:
o Addition
o Subtraction
o Multiplication
4. Accept user input for two numbers and the desired operation.
Example Output:
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
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:
Description:
The ShoppingCart class will store items as a dictionary with item names as keys and a tuple of (price,
quantity) as values.
Methods:
Algorithm:
4. Implement calculate_total() to iterate through the cart and compute the total price.
Example Output:
104
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
1 Bread(s) added to cart.
Shopping Cart:
Shopping Cart:
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:
Description:
The Employee class will have attributes like name, employee_id, department, and salary.
Algorithm:
Example Output:
Employee ID: 101, Name: John Doe, Department: IT, Salary: ₹75000
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:
Description:
The Student class will have attributes like name, student_id, course, and marks.
Algorithm:
Example Output:
Student ID: 201, Name: Alice Johnson, Course: Computer Science, Marks: 89%
107
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Viva-Voice Questions
1)What is a class in Python?
108
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 10: Programs on Exceptions.
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.
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:
Algorithm:
4. Catch specific exceptions like ZeroDivisionError, ValueError, and the custom exception separately.
Execution completed.
Execution completed.
Execution completed.
Execution completed.
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:
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:
Example Outputs:
112
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Enter first number: 10
Case 4: No Exception
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:
2. Use specific except blocks to catch known exceptions (ZeroDivisionError, ValueError, etc.).
Example Outputs:
Execution completed.
Execution completed.
114
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Enter first number: abc
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:
We use a try-except block to catch the error and prevent program crashes.
Algorithm:
Example Outputs:
Result: 5.0
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.
Algorithm:
Viva-Voice Questions
119
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Experiment 11: Programs Data Analysis
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.
Algorithm:
o 1D Array (Single-dimensional)
o 2D Array (Matrix)
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]]]
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:
Python provides various libraries to handle structured and unstructured data formats.
Algorithm:
[[ 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
sepal length (cm) sepal width (cm) petal length (cm) petal width (cm)
123
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
11c)Write a python script to create a data frame.
Aim:
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:
o Using a dictionary.
3. Print the DataFrame and its properties like shape, columns, and data types.
Example Output:
124
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
ID Name Age Score
DataFrame Information:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 4 entries, 0 to 3
0 ID 4 non-null int64
125
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
memory usage: 260.0+ bytes
None
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:
Algorithm:
3. Display the properties ndim, shape, size, and dtype for each array.
Example Output:
1D Array:
[1 2 3 4 5]
--------------------------------------------------
2D Array:
[[1 2 3]
[4 5 6]]
127
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
Shape (rows, columns): (2, 3)
--------------------------------------------------
3D Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
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:
3. Matrix Multiplication (A * B or np.dot(A, B)) → Computes the dot product of two matrices.
Algorithm:
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]]
[[-4 -4]
[-4 -4]]
[[19 22]
[43 50]]
[[ 5 12]
[21 32]]
Transpose of Matrix A:
[[1 3]
[2 4]]
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 also handle missing values and format the data accordingly.
Algorithm:
Alice 24 85
Bob 27 90
Charlie 22 88
David 25 78
Eve 23 95
Example Output:
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
Statistical Summary:
Age Score
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:
Algorithm:
Example Output:
Minimum Value: 10
Maximum Value: 50
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.
head() function in Pandas is used to display the first few rows of the dataset.
Algorithm:
Example Output:
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:
Description:
Pandas DataFrame allows easy data selection using indexing and slicing techniques.
Algorithm:
1. Import Pandas.
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 Marks
0 Alice 85
1 Bob 78
2 Charlie 90
3 David 88
4 Emma 76
5 Frank 95
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:
3 104 David 23 88 TX
0 101 Alice 20 85 NY
2 103 Charlie 21 90 SF
3 104 David 23 88 TX
5 106 Frank 24 95 DC
90
Charlie
Viva-Voice questions
1) What is NumPy, and what is it used for?
6) How do you read data from a CSV file into a Pandas DataFrame?
137
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE
8) What does ndim represent in a Pandas DataFrame?
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 "Time"
and the y-axis as "Value".
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.
Input:
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.
Input:
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:
3. Step 3: Plot the histogram using the data and chosen number of bins.
Input:
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).
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.
Input:
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.
5. Step 5: Add percentages to each slice showing the proportion of the category relative to the total.
Input:
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
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?
7) How do you decide the number of bins to use when creating a histogram?
144
PYTHON PROGRAMMING LAB MANNUAL
LENDI INSTITUTE OF ENGINEERING & TECHNOLOGY-DEPARTMENT OF CSE