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

Python Lab Exercises Record 2025

The document outlines a Python lab record for various courses, detailing a schedule of exercises with corresponding dates. Each exercise includes tasks such as demonstrating operators, performing operations on lists, and creating classes. The lab exercises are structured for students to practice fundamental Python programming concepts and techniques.

Uploaded by

hoshika.gunturu
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 views62 pages

Python Lab Exercises Record 2025

The document outlines a Python lab record for various courses, detailing a schedule of exercises with corresponding dates. Each exercise includes tasks such as demonstrating operators, performing operations on lists, and creating classes. The lab exercises are structured for students to practice fundamental Python programming concepts and techniques.

Uploaded by

hoshika.gunturu
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

23A05304 PYTHON LAB RECORD

DATE SHEET FOR

CSE - A
Python Lab-Exercises
[Link] Name of the Experiment Date
Demonstrate the following operators in Python with suitable
examples.
1 i) Arithmetic Operators ii) Relational Operators iii) 30-06-2025
Assignment Operators iv) Logical Operators v) Bit wise
Operators vi) Ternary Operator vii) Membership
Operators viii) Identity Operators
Write a python program to add and multiply two
2 07-07-2025
complex numbers
Write a Program to display all prime numbers
3 14-07-2025
within an interval
Write a program to define a function with
4 multiple return values. 21-07-2025

Write a program to perform the given operations


5 on a list: 28-07-2025
i. Addition ii. Insertion iii. slicing
Write a program to create tuples (name, age,
address, college) for at least two members and
6 concatenate the tuples and print the concatenated 04-08-2025
tuples

Write a program to check if a given key exists in


7 11-08-2025
a dictionary or not
Write a program to sort words in a file and put
them in another file. The output file should have
8 25-08-2025
only lower-case words, so any upper-case words
from source must be lowered
Write a program Python program to print each
9 01-09-2025
line of a file in reverse order.
Write a python program to create, display,
append, insert and reverse the order of the items
10 08-09-2025
in the array

Page | 1
Write a program to add, transpose and multiply
11 15-09-2025
two matrices.
Write a Python program to create a class that
12 represents a shape. Include methods to calculate 22-09-2025
its area and perimeter
Python program to check whether a JSON string
13 29-09-2025
contains complex object or not.
Python program to demonstrate use of ndim,
14 06-10-2025
shape, size, dtype.
Select any two columns from the above data
frame, and observe the change in one attribute
15 13-10-2025
with respect to other attribute with scatter and
plot operations in matplotlib

Page | 2
23A05304 PYTHON LAB RECORD
DATE SHEET FOR

CSE - B
Python Lab-Exercises
[Link] Name of the Experiment Date
Demonstrate the following operators in Python with suitable
examples.
1 i) Arithmetic Operators ii) Relational Operators iii) 01-07-2025
Assignment Operators iv) Logical Operators v) Bit wise
Operators vi) Ternary Operator vii) Membership
Operators viii) Identity Operators
Write a python program to add and multiply two
2 complex numbers 08-07-2025

Write a Program to display all prime numbers


3 15-07-2025
within an interval
Write a program to define a function with
4 multiple return values. 22-07-2025

Write a program to perform the given operations


on a list:
5 29-07-2025
i. Addition ii. Insertion iii. Slicing

Write a program to create tuples (name, age,


address, college) for at least two members and
6 08-08-2025
concatenate the tuples and print the concatenated
tuples
Write a program to check if a given key exists in
7 12-08-2025
a dictionary or not
Write a program to sort words in a file and put
them in another file. The output file should have
8 19-08-2025
only lower-case words, so any upper-case words
from source must be lowered
Write a program Python program to print each
9 26-08-2025
line of a file in reverse order.
Write a python program to create, display,
append, insert and reverse the order of the items
10 02-09-2025
in the array

Page | 3
Write a program to add, transpose and multiply
11 09-09-2025
two matrices.
Write a Python program to create a class that
12 represents a shape. Include methods to calculate 16-09-2025
its area and perimeter
Python program to check whether a JSON string
13 23-09-2025
contains complex object or not.
Python program to demonstrate use of ndim,
14 07-10-2025
shape, size, dtype.
Select any two columns from the above data
frame, and observe the change in one attribute
15 14-10-2025
with respect to other attribute with scatter and
plot operations in matplotlib

Page | 4
23A05304 PYTHON LAB RECORD
DATE SHEET FOR

AI & DS
Python Lab-Exercises
[Link] Name of the Experiment Date
Demonstrate the following operators in Python with suitable
examples.
i) Arithmetic Operators ii) Relational Operators iii)
1 Assignment Operators iv) Logical Operators v) Bit wise 02-07-2025
Operators vi) Ternary Operator vii) Membership
Operators viii) Identity Operators

Write a python program to add and multiply two


2 complex numbers 09-07-2025

Write a Program to display all prime numbers


3 within an interval 16-07-2025

Write a program to define a function with


4 multiple return values. 23-07-2025

Write a program to perform the given


5 operations on a list: 30-07-2025
i. Addition ii. Insertion iii. slicing
Write a program to create tuples (name, age,
address, college) for at least two members and
6 06-08-2025
concatenate the tuples and print the concatenated
tuples
Write a program to check if a given key exists in
7 13-08-2025
a dictionary or not
Write a program to sort words in a file and put
them in another file. The output file should have
8 20-08-2025
only lower-case words, so any upper-case words
from source must be lowered
Write a program Python program to print each
9 03-09-2025
line of a file in reverse order.
Write a python program to create, display,
10 append, insert and reverse the order of the items 10-09-2025
in the array

Page | 5
Write a program to add, transpose and multiply
11 17-09-2025
two matrices.
Write a Python program to create a class that
12 represents a shape. Include methods to calculate 24-09-2025
its area and perimeter
Python program to check whether a JSON string
13 01-10-2025
contains complex object or not.
Python program to demonstrate use of ndim,
14 08-10-2025
shape, size, dtype.
Select any two columns from the above data
frame, and observe the change in one attribute
15 15-10-2025
with respect to other attribute with scatter and
plot operations in matplotlib

Page | 6
23A05304 PYTHON LAB RECORD
DATE SHEET FOR

ECE
Python Lab-Exercises
[Link] Name of the Experiment Date
Demonstrate the following operators in Python with suitable
examples.
i) Arithmetic Operators ii) Relational Operators iii)
1 Assignment Operators iv) Logical Operators v) Bit wise 03-07-2025
Operators vi) Ternary Operator vii) Membership
Operators viii) Identity Operators

Write a python program to add and multiply two


2 complex numbers 10-07-2025

Write a Program to display all prime numbers


3 17-07-2025
within an interval
Write a program to define a function with
4 24-07-2025
multiple return values.
Write a program to perform the given operations
on a list:
5 31-07-2025
i. Addition ii. Insertion iii. slicing

Write a program to create tuples (name, age,


address, college) for at least two members and
6 concatenate the tuples and print the concatenated 07-08-2025
tuples

Write a program to check if a given key exists in


7 14-08-2025
a dictionary or not
Write a program to sort words in a file and put
them in another file. The output file should have
8 21-08-2025
only lower-case words, so any upper-case words
from source must be lowered
Write a program Python program to print each
9 28-08-2025
line of a file in reverse order.
Write a python program to create, display,
10 append, insert and reverse the order of the items 04-09-2025
in the array

Page | 7
Write a program to add, transpose and multiply
11 11-09-2025
two matrices.
Write a Python program to create a class that
12 represents a shape. Include methods to calculate 18-09-2025
its area and perimeter
Python program to check whether a JSON string
13 25-09-2025
contains complex object or not.
Python program to demonstrate use of ndim,
14 09-10-2025
shape, size, dtype.
Select any two columns from the above data
frame, and observe the change in one attribute
15 16-10-2025
with respect to other attribute with scatter and
plot operations in matplotlib

Page | 8
Exercise. No: 1 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) Ternary Operator vii) Membership
Operators viii) Identity Operators
Aim: To perform following operators

i) Arithmetic Operators
ii) Relational Operators
iii) Assignment Operators
iv) Logical Operators
v) Bit wise Operators
vi) Ternary Operator
vii) Membership Operators
viii) Identity Operators

Algorithm

i) Arithmetic Operators
Take two numeric inputs: a, b
Apply each operator:
• sum = a + b
• diff = a - b
• prod = a * b
• quot = a / b (float division)
• int_quot = a // b (integer division)
• mod = a % b
• power = a ** b
Return or display results

ii) Relational Operators


Take two inputs: x, y
Compare using each operator:
• x > y, x < y, x >= y, x <= y, x == y, x != y
Return Boolean results for each comparison

Page | 9
iii) Assignment Operators
Initialize a variable: val = initial_value
Apply compound assignments:
• val += 5 → val = val + 5
• val *= 2 → val = val * 2
• etc.
Track changes to val after each operation

iv) Logical Operators


Take two Boolean inputs: A, B
Evaluate:
• A and B → True if both are True
• A or B → True if at least one is True
• not A → Inverts A
Return logical outcomes

v) Bitwise Operators
Take two integers: m, n
Apply bitwise operations:
• m & n → AND
• m | n → OR
• m ^ n → XOR
• ~m → NOT
• m << 2 → Left shift by 2 bits
• m >> 2 → Right shift by 2 bits
Return binary or decimal results

vi) Ternary Operators


Take inputs: a, b, condition
Evaluate:
• If condition is True → result = a
• Else → result = b
Return result

Page | 10
vii) Membership Operators
Take an element e and a collection C (list, set, string, etc.)
Check:
• e in C → True if e exists in C
• e not in C → True if e does not exist in C
Return Boolean result

viii) Identity Operators


Take two variables: x, y
Check:
o x is y → True if both refer to the same object
o x is not y → True if they refer to different objects
Return Boolean result

Page | 11
Source Code:
#Python Program to demonstrate Arithmetic Operations

# i) Arithmetic Operators
a = 10
b = 5
print("Arithmetic Operators:")
print("a + b:", a+b) # Addition
print("a - b:", a-b) # Subtraction
print("a * b:", a*b) # Multiplication
print("a / b:", a/b) # Division
print("a % b:", a % b) # Modulus (remainder)
print("a ** b:", a **b) # Exponentiation
print("a // b:", a //b) # Floor Division
print("\n")

# ii) Relational Operators


x = 10
y = 20
print("Relational Operators:")
print("x == y:", x ==y) # Equal to
print("x != y:", x != y) # Not equal to
print("x > y:", x > y) # Greater than
print("x < y:", x < y) # Less than
print("x >= y:", x >= y) # Greater than or equal to
print("x <= y:", x <= y) # Less than or equal to
print("\n")

# iii) Assignment Operators


z = 5
z += 3 # z = z + 3
print("z += 3:", z) # z = z + 3
z -= 2 # z = z - 2
print("z -= 2:", z) # z = z - 2
z *= 2 # z = z * 2
print("z *= 2:", z) # z = z * 2
z /= 4 # z = z / 4
print("z /= 4:",z) # z = z / 4
print("\n")

Page | 12
# iv) Logical Operators
a = True
b = False
print("Logical Operators:")
print("a and b:", a and b) # Logical AND
print("a or b:", a or b) # Logical OR
print("not a:", not a) # Logical NOT
print("\n")

# v) Bitwise Operators
p = 5 # Binary: 0101
q = 3 # Binary: 0011
print("Bitwise Operators:")
print("p & q:", p & q) # AND
print("p | q:", p | q) # OR
print("p ^ q:", p ^ q) # XOR
print("~p:",~p) # NOT
print("p << 1:", p << 1) # Left shift
print("p >> 1:", p >> 1) # Right shift
print("\n")

# vi) Ternary Operator (Conditional Expression)


age = 18
status = "Adult" if age >= 18 else "Minor"
print("Ternary Operator::", status)
print("\n")

# vii) Membership Operators


list_example = [1, 2, 3, 4, 5]
print("Membership Operators:")
print("3 in list_example:", 3 in list_example) # checks if 3 is
in the list
print("6 not in list_example:", 6 not in list_example) # checks
if 6 is not in the list
print("\n")

Page | 13
# viii) Identity Operators
a = 10
b = 10
c = [1, 2, 3]
d = [1, 2, 3]
print("Identity Operators:")
print("a is b:", a is b) # Checks if a and b refer to the same
object
print("a is not b:", a is not b) # Checks if a and b do not
refer to the same object
print("c is d:", c is d) # False, as both lists have same
content but are different objects
print("c == d:", c == d) # True, content is same

Page | 14
Output
#Arithmetic Operators:
a + b: 15
a - b: 5
a * b: 50
a / b: 2.0
a % b: 0
a ** b: 100000
a // b: 2

#Relational Operators
x == y: False
x != y: True
x > y: False
x < y: True
x >= y: False
x <= y: True

#Assingment Operators
z += 3: 8
z -= 2: 6
z *= 2: 12
z /= 4: 3.0

#Logical Operators:
a and b: False
a or b: True
not a: False

#Bitwise Operators:
p & q: 1
p | q: 7
p ^ q: 6
~p: -6
p << 1: 10
p >> 1: 2

Page | 15
#Ternary Operator:: Adult
Membership Operators:
3 in list_example: True
6 not in list_example: True

#Identity Operators:
a is b: True
a is not b: False
c is d: False
c == d: True

Result: Thus, operations on operators demonstrated successfully

Page | 16
Exercise 2: Write a python program to add and multiply two complex
numbers
Aim: To demonstrate add and multiply two complex numbers
Algorithm to add two complex numbers

Start.
1. Input two complex numbers, 𝑧1=𝑎+𝑖𝑏 and 𝑧2=𝑐+𝑖𝑑
2. Calculate the real part of the sum: 𝑟𝑒𝑎𝑙_𝑠𝑢𝑚=𝑎+𝑐
3. Calculate the imaginary part of the sum: 𝑖𝑚𝑎𝑔𝑖𝑛𝑎𝑟𝑦_𝑠𝑢𝑚=𝑏+𝑑
4. Output the result as a new complex number: 𝑟𝑒𝑎𝑙_𝑠𝑢𝑚+𝑖(𝑖𝑚𝑎𝑔𝑖𝑛𝑎𝑟𝑦_𝑠𝑢𝑚)
End.

Algorithm to multiply two complex numbers


Start.
1. Input two complex numbers, 𝑧1=𝑎+𝑖𝑏 and 𝑧2=𝑐+𝑖𝑑
2. Calculate the real part of the product: 𝑟𝑒𝑎𝑙_𝑝𝑟𝑜𝑑𝑢𝑐𝑡=(𝑎⋅𝑐)−(𝑏⋅𝑑)
3. Calculate the imaginary part of the product: 𝑖𝑚𝑎𝑔𝑖𝑛𝑎𝑟𝑦_𝑝𝑟𝑜𝑑𝑢𝑐𝑡=(𝑎⋅𝑑)+(𝑏⋅𝑐)
4. Output the result as a new complex number: 𝑟𝑒𝑎𝑙_𝑝𝑟𝑜𝑑𝑢𝑐𝑡+𝑖(𝑖𝑚𝑎𝑔𝑖𝑛𝑎𝑟𝑦_𝑝𝑟𝑜𝑑𝑢𝑐𝑡)
End.

Page | 17
Source Code
# Accept real and imaginary parts for the first complex number
a = float(input("Enter real part of first number: "))
b = float(input("Enter imaginary part of first number: "))

# Accept real and imaginary parts for the second complex number
c = float(input("Enter real part of second number: "))
d = float(input("Enter imaginary part of second number: "))

# Complex addition: (a + c) + (b + d)j


sum_real = a + c
sum_imag = b + d

# Complex multiplication: (a + b j) × (c + d j)
# = (a*c − b*d) + (a*d + b*c) j
mul_real = a * c - b * d
mul_imag = a * d + b * c

# Print results
print(f"Sum: {sum_real} + {sum_imag}j")
print(f"Product: {mul_real} + {mul_imag}j")

Output
Enter real part of first number: 10
Enter imaginary part of first number: 6
Enter real part of second number: 12
Enter imaginary part of second number: -5
Sum: 22.0 + 1.0j
Product: 150.0 + 22.0j

Result: Thus, Addition and Multiplication of two complex numbers demonstrated successfully.

Page | 18
Exercise 3: Write a Program to display all prime numbers within an
interval

Aim: To display all prime numbers within an interval

Algorithm

Step 1: Start the Program


Step 2: Input Handling
• Use a try block to:
• Prompt the user to enter the lower bound of the interval.
• Prompt the user to enter the upper bound of the interval.
• Convert both inputs to integers.
Step 3: Validate and Adjust Bounds
• If the lower bound is less than 2, set it to 2 (since prime numbers start from 2).
Step 4: Prime Number Detection
• Loop through each number num from lower to upper (inclusive):
• Assume num is prime by setting a flag is_prime = True.
• Loop through all integers i from 2 to num - 1:
o If num % i == 0, set is_prime = False and break the loop.
• If is_prime is still True, print num as a prime number.
Step 5: Handle Invalid Input
• Use an except block to catch ValueError if the user enters non-integer input.
• Display an error message.
Step 6: Final Message
• Use a finally block to print a message indicating the program has completed execution.
Step 7: End the Program

Page | 19
Source Code:
# Program to display prime numbers within an interval using try-except-finally

try:
# Get the lower and upper bounds of the interval from the user
lower = int(input("Enter the lower bound of the interval: "))
upper = int(input("Enter the upper bound of the interval: "))

print(f"\nPrime numbers between {lower} and {upper} are:")

# Ensure the lower bound is at least 2, as prime numbers must be greater than 1
if lower < 2:
lower = 2

# Loop through each number in the specified range


for num in range(lower, upper + 1):
is_prime = True # Assume the current number is prime initially

# Check for factors from 2 up to the number itself (exclusive)


for i in range(2, num):
if num % i == 0:
is_prime = False
break # Exit the inner loop since it's already confirmed not to be prime

# If the inner loop completes without finding any factors, the number is prime
if is_prime:
print(num)

except ValueError:
print("\nInvalid input! Please enter valid integers for the interval.")

finally:
print("\nProgram execution completed.")

Page | 20
Output
Enter the lower bound of the interval: 10
Enter the upper bound of the interval: 50

Prime numbers between 10 and 50 are:


11
13
17
19
23
29
31
37
41
43
47

Program execution completed.

Result: Thus, display of prime numbers within a given range is successful

Page | 21
Exercise 4: Write a program to define a function with multiple
return values.
Aim: To define a function with multiple return valves

Algorithm
1. Define a function signature that specifies the input parameters.
2. Determine the values to be returned. Inside the function, perform the necessary
computations to produce the multiple results.
3. Choose a method for bundling the return values based on the programming language's
capabilities:
o Return a collection type: Place the values into a data structure like a tuple, list,
array, or dictionary, and return that single collection.
o Return a custom object (struct or class): Define a custom class or struct to hold
the multiple values as attributes. Instantiate this object inside the function and
return the instance.
o Use output parameters: For languages that support pass-by-reference (like C or
C#), pass variables into the function by reference or as pointers. The function can
then modify the original variables, effectively "returning" multiple values
without using a formal return statement.
o Use native multiple return syntax: Some languages, like Python and Go, have
built-in support for returning multiple values in a single return statement.
4. Write the return statement using the chosen method.
5. Write the calling code to receive and unpack the returned values into separate variables.

Source Code

def name():
return "Python","Programming"

# print the tuple with the returned values


print(name())

# get the individual items


name_1, name_2 = name()
print(name_1, name_2)

Output
('Python', 'Programming')
Python Programming

Result: Thus, multiple return values were obtained from the function definition

Page | 22
Exercise 5:
Write a program to perform the given operations on a list:
i. Addition ii. Insertion iii. slicing

Aim: To perform following operations on list


i) Addition
ii) Insertion
iii) Slicing

Algorithm
Start
1. Initialize an empty list called my_list.
2. Prompt user to enter the number of elements to add (n).
3. Repeat the following steps n times:
o Ask the user to input an element.
o Append the element to my_list.
4. Display the list after addition.
5. Ask user for:
o An element to insert (insert_element)
o The index at which to insert (insert_index)
6. Insert insert_element at insert_index in my_list.
7. Display the list after insertion.
8. Ask user for:
o Start index for slicing (start_index)
o End index for slicing (end_index)
9. Slice the list from start_index to end_index and store in sliced_list.
10. Display the sliced portion.
End

Page | 23
Source Code
# Program to perform addition, insertion, and slicing on a list

try:
# Create an initial list
my_list = []

# Addition: Append elements to the list

n = int(input("How many elements do you want to add to the


list? "))
print("Enter", n, "elements:")
for i in range(n):
element = input("Element " + str(i + 1) + ": ")
my_list.append(element)

print("\nList after addition:", my_list)

# Insertion: Insert an element at a specific index

insert_element = input("\nEnter an element to insert: ")


insert_index = int(input("Enter the index at which to
insert the element: "))
my_list.insert(insert_index, insert_element)

print("List after insertion:", my_list)

# Slicing: Display a slice of the list

start_index = int(input("\nEnter the start index for


slicing: "))
end_index = int(input("Enter the end index for slicing: "))
sliced_list = my_list[start_index:end_index]

print("Sliced portion of the list:", sliced_list)

except ValueError:
print("\nInvalid input! Please enter valid integers where
required.")

finally:
print("\nProgram execution completed.")

Page | 24
Output

How many elements do you want to add to the list? 8


Enter 8 elements:
Element 1: 10
Element 2: 5
Element 3: 6
Element 4: 2
Element 5: 3
Element 6: 8
Element 7: 9
Element 8: 4

List after addition: ['10', '5', '6', '2', '3', '8', '9', '4']

Enter an element to insert: 25


Enter the index at which to insert the element: 3
List after insertion: ['10', '5', '6', '25', '2', '3', '8', '9', '4']

Enter the start index for slicing: 0


Enter the end index for slicing: 5
Sliced portion of the list: ['10', '5', '6', '25', '2']

Program execution completed.

Result: Thus, the following operations Insertion, Addition, Slicing demonstrated successfully
using lists

Page | 25
Exercise 6: Write a program to create tuples (name, age, address,
college) for at least two members and concatenate the tuples and print
the concatenated tuples
Aim: To accept two tuples with following details (name,age,addres,college)
and print the concatenated tuples
Algorithm
Start
1. Define a tuple member1 with four elements:
o Name
o Age
o Address
o College
2. Define another tuple member2 with the same four elements:
o Name
o Age
o Address
o College
3. Concatenate member1 and member2 using the + operator and store the result in
combined_tuple.
4. Display the combined_tuple.
End

Source Code
# Program to concatenate two tuples
# Create tuples for two members
t1 = ("Ravi", 21, "2-45 Bazar Street", "Chittoor")
t2 = ("Raju", 22, "20-45 Gandi Raod", "Chittoor")

# Concatenate the tuples


conct_tuple = t1 + t2

# Print the concatenated tuple


print("Concatenated Tuple:")
print(conct_tuple)

Output
Concatenated Tuple:
('Ravi', 21, '2-45 Bazar Street', 'Chittoor', 'Raju', 22, '20-45
Gandi Road', 'Chittoor')

Result: Thus, concatenation of tuples successful

Page | 26
Exercise 7: Write a program to check if a given key exists in a
dictionary or not
Aim: To check whether a given key exists or not in a dictionary
Algorithm
1. Declare and initialize a dictionary to have some key-value pairs.
2. Take a key from the user and store it in a variable.
3. Using an if statement and the in operator, check if the key is present in the dictionary using
the [Link]() method.
4. If it is present, print the value of the key.
5. If it isn’t present, display that the key isn’t present in the dictionary.
6. Exit.

Source Code
# Program to check if a key exists in a dictionary and display
its value with exception handling

# Sample dictionary
my_dict = {
"name": "Ravi Kumar", "age": 25, "location": "Chittoor",
"profession": "Engineer"
}

try:
# Ask user for the key to check
key_check = input("Enter the key to check: ")

# Check if the key exists and display its value


if key_check in my_dict:
print("Yes, the key '" + key_check + "' exists in the
dictionary.")
print("Value:", my_dict[key_check])
else:
print("No, the key '" + key_check + "' does not exist in
the dictionary.")

except Exception as e:
print("An unexpected error occurred:", str(e))

Output
Enter the key to check: location
Yes, the key 'location' exists in the dictionary.
Value: Chittoor

Result: Thus, checking for a key and its value demonstrated successfully

Page | 27
Exercise 8: Write a program to sort words in a file and put them in
another file. The output file should have only lower-case words, so any
upper-case words from source must be lowered.

Aim: To demonstrate sorting of words in a file and convert all the words into
lower case in output file

Algorithm
Step 1: Input
• input_file: Path to the source file containing words (could be mixed case)
• output_file: Path where the sorted lowercase words will be saved

Step 2: Open the input_file in read mode.


Step 3: Read all the contents of the file into a single string.
Step 4: Convert the entire string to lowercase.
Step 5: Extract words from the string:
• Remove punctuation if necessary.
• Split the string into words (by whitespace or using regex).
Step 6: Sort the list of words alphabetically.
Step 7: Open the output_file in write mode.
Step 8: Write each sorted word into the output_file, one word per line.
Step 9: Close both input and output files.

Step 10: Output:


• A new file (output_file) containing all the words from the source file,
converted to lowercase and sorted alphabetically, one word per line.

Source Code:
Page | 28
#------------------------------------------------------
#Python program to sort words in a file and put them in
another file
#The output file has only lower-case words
#Sort_Convert_uppertolower.py
#------------------------------------------------------

# create a input file


f=open("G:\\TrainPython\\[Link]","a")

#Enter a input string


user_input=input("Enter an input string::")

#Write the string into a file


f=open("G:\\TrainPython\\[Link]","w")
x=[Link](user_input)

# read the data from a file


f=open("G:\\TrainPython\\[Link]","r")
lines = [Link]()
print(lines,end='')
[Link]()

#Convert to lower case


lcase = [Link]()
print(lcase)

#Extract words in the complete string


word=[Link]()
print(word)

#Sort words
sorted_words = sorted(word)
print(sorted_words)

# create a output file


f=open("G:\\TrainPython\\[Link]","a")

# to write the data into a file

Page | 29
f = open("G:\\TrainPython\\[Link]","w")
result = [Link](" ".join(sorted_words))
print("Output file written Succesfully")
[Link]()

Test data

[Link]

[Link]

Page | 30
Exercise 9: Write a program Python program to print each line of a
file in reverse order.
Aim: To print each line of a file in reverse order
Algorithm
Start
1. Create an empty list inputs.
2. Repeat steps 3–4 for 4 times (or number of inputs required):
3. Accept a string from the user.
4. Append the string with a newline "\n" into the list inputs.
5. Open [Link] in write mode.
6. Write all the strings from inputs into [Link].
7. Close the file.
8. Open [Link] in read mode.
9. Read all lines from the file into a list lines.
[Link] each line in lines:
10.1 Remove the newline character (use rstrip()).
10.2 Reverse the string ([::-1]).
10.3 Add a newline character at the end.
10.4 Store the reversed string in a new list reversed_lines.
[Link] both the original lines and the reversed lines on the screen.
[Link] [Link] in write mode.
[Link] all reversed_lines into [Link].
[Link] the file.
[Link] message “Reversal of each line successful!”
Stop.

Page | 31
Source Code:
# Print each line of file in reverse order
# create a input file
f=open("E:\\College\\BTech\\[Link]","a")

#Take input and write to input file


inputs = []
for i in range(1, 5):
user_input = input("Enter an input string:\n ")
# store each input as a new line
[Link](user_input + "\n")

# Write inputs to input file


f=open("E:\\College\\BTech\\[Link]", "w")
[Link](inputs)

# Read the file line by line


f=open("E:\\College\\BTech\\[Link]", "r")
lines = [Link]()

print("\nOriginal Content:")
for line in lines:
print(line, end="")

Page | 32
# Reverse each line separately
#for line in lines:
reversed_lines = [[Link]()[::-1] + "\n" for line in
lines]

print("\nReversed Content (line by line):")


for line in reversed_lines:
print(line, end="")

# create a output file


f=open("E:\\College\\BTech\\[Link]", "w")

# Write reversed lines into output file


f=open("E:\\College\\BTech\\[Link]", "w")
[Link](reversed_lines)

print("\nReversal of each line successful!\n")

Page | 33
Test data
Input file: [Link]

Output

Output [Link]

Page | 34
Exercise 10: Write a python program to create, display, append, insert
and reverse the order of the items in the array.
Aim: To demonstrate create, insert, append and display operations in an array
then reverse the order of items within an array
Algorithm
Start
1. Import array module.
2. Create an array arr with initial elements.
3. Display the original array.
4. Append Operation:
o Use [Link](item) to add a new element at the end.
o Display the array.
5. Insert Operation:
o Use [Link](position, item) to insert element at a specific index.
o Display the array.
6. Reverse Operation:
o Use [Link]() to reverse the order of array elements.
o Display the reversed array.
Stop

Page | 35
Source Code:
def display_menu():
print("\n====== Array Operations Menu ======")
print("1. Create Array")
print("2. Display Array")
print("3. Append Item")
print("4. Insert Item at Position")
print("5. Reverse Array")
print("6. Exit")

def main():
array = []

while True:
display_menu()
try:
choice = int(input("Enter your choice (1-6):
"))
except ValueError:
print("Please enter a valid number.")
continue

if choice == 1:
[Link]()
try:
n = int(input("How many elements do you want to
add? "))
for i in range(n):
element = int(input("Enter element
" + str(i + 1) + ": "))
[Link](element)
print("Array created successfully.")
except ValueError:
print("Invalid input. Please enter
integers only.")

elif choice == 2:
print("Current Array:", array)

elif choice == 3:

Page | 36
try:
item = int(input("Enter item to append: "))
[Link](item)
print(item, "appended to array.")
except ValueError:
print("Please enter a valid integer.")

elif choice == 4:
try:
item = int(input("Enter item to insert: "))
pos = int(input("Enter position (0-based index): "))
if 0 <= pos <= len(array):
[Link](pos, item)
print(item, "inserted at position", pos)
else:
print("Invalid position.")
except ValueError:
print("Please enter valid integers.")

elif choice == 5:
[Link]()
print("Array reversed.")

elif choice == 6:
print("Exiting program. Have a great day!")
break

else:
print("Invalid choice. Please select from 1
to 6.")

if __name__ == "__main__":
main()

Page | 37
Output

====== Array Operations Menu ======


1. Create Array
2. Display Array
3. Append Item
4. Insert Item at Position
5. Reverse Array
6. Exit
Enter your choice (1-6): 1
How many elements do you want to add? 5
Enter element 1: 10
Enter element 2: 15
Enter element 3: 25
Enter element 4: 30
Enter element 5: 40
Array created successfully.

====== Array Operations Menu ======


1. Create Array
2. Display Array
3. Append Item
4. Insert Item at Position
5. Reverse Array
6. Exit
Enter your choice (1-6): 2
Current Array: [10, 15, 25, 30, 40]

====== Array Operations Menu ======


1. Create Array
2. Display Array
3. Append Item
4. Insert Item at Position
5. Reverse Array
6. Exit
Enter your choice (1-6): 3
Enter item to append: 45
45 appended to array.

====== Array Operations Menu ======

Page | 38
1. Create Array
2. Display Array
3. Append Item
4. Insert Item at Position
5. Reverse Array
6. Exit
Enter your choice (1-6): 2
Current Array: [10, 15, 25, 30, 40, 45]

====== Array Operations Menu ======


1. Create Array
2. Display Array
3. Append Item
4. Insert Item at Position
5. Reverse Array
6. Exit
Enter your choice (1-6): 4
Enter item to insert: 2
Enter position (0-based index): 2
2 inserted at position 2

====== Array Operations Menu ======


1. Create Array
2. Display Array
3. Append Item
4. Insert Item at Position
5. Reverse Array
6. Exit
Enter your choice (1-6): 2
Current Array: [10, 15, 2, 25, 30, 40, 45]

====== Array Operations Menu ======


1. Create Array
2. Display Array
3. Append Item
4. Insert Item at Position
5. Reverse Array
6. Exit
Enter your choice (1-6): 5
Array reversed.

Page | 39
====== Array Operations Menu ======
1. Create Array
2. Display Array
3. Append Item
4. Insert Item at Position
5. Reverse Array
6. Exit
Enter your choice (1-6): 2
Current Array: [45, 40, 30, 25, 2, 15, 10]

====== Array Operations Menu ======


1. Create Array
2. Display Array
3. Append Item
4. Insert Item at Position
5. Reverse Array
6. Exit
Enter your choice (1-6):

Result: Thus, create, display, append, insert item at position ‘n’, reversal of
elements using arrays demonstrated successfully

Page | 40
Exercise 11: Write a program to add, transpose and multiply two
matrices.

Aim: To demonstrate add , transpose and multiply operations on matrices


Algorithm

Start
1. Input Matrices
1.1 Ask the user to enter the number of rows and columns for Matrix A.
1.2 Read the elements row by row and store them in a 2D list.
1.3 Ask the user to enter the number of rows and columns for Matrix B.
1.4 Read the elements row by row and store them in a 2D list.
Case 1: Add Matrices
o Check if dimensions of A and B are the same.
o If yes, add corresponding elements C[i][j] = A[i][j] + B[i][j].
o Print the result.
o If dimensions don’t match, display error message.
Case 2: Transpose Matrix A
o Swap rows with columns.
o Print the transposed matrix.
Case 3: Transpose Matrix B
o Swap rows with columns.
o Print the transposed matrix.
Case 4: Multiply Matrices
o Check if columns of A = rows of B.
o If yes, compute multiplication:
o C[i][j] = Σ (A[i][k] × B[k][j]) for k = 0 to (columns of A – 1)
o Print the result.
o If dimensions don’t match, display error message.
Case 5: Exit
o Display message “Exiting program. Goodbye!” and terminate loop.
Default Case
o If the choice is invalid, display error message.
Stop

Page | 41
Source Code:

def input_matrix(name):
rows = int(input(f"Enter number of rows for {name}: "))
cols = int(input(f"Enter number of columns for {name}: "))
print(f"Enter elements for {name} row-wise:")
matrix = []
for i in range(rows):
row = list(map(int, input(f"Row {i+1}: ").split()))
if len(row) != cols:
print("Invalid number of elements. Try again.")
return input_matrix(name)
[Link](row)
return matrix

def print_matrix(matrix):
for row in matrix:
print(" ".join(map(str, row)))

def add_matrices(A, B):


if len(A) != len(B) or len(A[0]) != len(B[0]):
print("Addition not possible. Matrices must be of same
dimensions.")
return
result = [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i
in range(len(A))]
print("Result of Addition:")
print_matrix(result)

def transpose_matrix(matrix):
result = [[matrix[j][i] for j in range(len(matrix))] for i in
range(len(matrix[0]))]
print("Transposed Matrix:")
print_matrix(result)

def multiply_matrices(A, B):


if len(A[0]) != len(B):
print("Multiplication not possible. Columns of A must
equal rows of B.")
return
result = [[sum(A[i][k] * B[k][j] for k in range(len(B))) for
j in range(len(B[0]))] for i in range(len(A))]
print("Result of Multiplication:")
print_matrix(result)

# Main Menu
print("Matrix Operations Menu")

Page | 42
A = input_matrix("Matrix A")
B = input_matrix("Matrix B")

while True:
print("\nChoose an operation:")
print("1. Add Matrices")
print("2. Transpose Matrix A")
print("3. Transpose Matrix B")
print("4. Multiply Matrices")
print("5. Exit")

choice = input("Enter your choice (1-5): ")

if choice == '1':
add_matrices(A, B)
elif choice == '2':
transpose_matrix(A)
elif choice == '3':
transpose_matrix(B)
elif choice == '4':
multiply_matrices(A, B)
elif choice == '5':
print("Exiting program. Goodbye!")
break
else:
print("Invalid choice. Please try again.")

Page | 43
Output
Matrix Operations Menu
Enter number of rows for Matrix A: 3
Enter number of columns for Matrix A: 3
Enter elements for Matrix A row-wise:
Row 1: 2 4 3
Row 2: 3 6 5
Row 3: 2 2 2
Enter number of rows for Matrix B: 3
Enter number of columns for Matrix B: 3
Enter elements for Matrix B row-wise:
Row 1: 3 6 9
Row 2: 3 3 4
Row 3: 2 1 3

Choose an operation:
1. Add Matrices
2. Transpose Matrix A
3. Transpose Matrix B
4. Multiply Matrices
5. Exit
Enter your choice (1-5): 1
Result of Addition:
5 10 12
6 9 9
4 3 5

Choose an operation:
1. Add Matrices
2. Transpose Matrix A
3. Transpose Matrix B
4. Multiply Matrices
5. Exit
Enter your choice (1-5): 2
Transposed Matrix:
2 3 2
4 6 2
3 5 2

Choose an operation:
1. Add Matrices
2. Transpose Matrix A
3. Transpose Matrix B
4. Multiply Matrices
5. Exit
Enter your choice (1-5): 3

Page | 44
Transposed Matrix:
3 3 2
6 3 1
9 4 3

Choose an operation:
1. Add Matrices
2. Transpose Matrix A
3. Transpose Matrix B
4. Multiply Matrices
5. Exit
Enter your choice (1-5): 4
Result of Multiplication:
24 27 43
37 41 66
16 20 32

Choose an operation:
1. Add Matrices
2. Transpose Matrix A
3. Transpose Matrix B
4. Multiply Matrices
5. Exit
Enter your choice (1-5): 5
Exiting program. Goodbye!

Page | 45
Exercise 12. Write a Python program to create a class that represents
a shape. Include methods to calculate its area and perimeter.
Aim: To demonstrate polymorphism in python
Algorithm
BEGIN
TRY
// -------- Circle --------
PRINT "Enter radius of circle: "
READ radius
CONVERT radius TO FLOAT
area_circle ← π * radius * radius
perimeter_circle ← 2 * π * radius
PRINT "Circle Area = ", area_circle
PRINT "Circle Perimeter = ", perimeter_circle
// -------- Square --------
PRINT "Enter side of square: "
READ side
CONVERT side TO FLOAT
area_square ← side * side
perimeter_square ← 4 * side
PRINT "Square Area = ", area_square
PRINT "Square Perimeter = ", perimeter_square

// -------- Triangle --------


PRINT "Enter sides of triangle (a, b, c): "
READ a, b, c
CONVERT a, b, c TO FLOAT

IF (a + b > c) AND (a + c > b) AND (b + c > a) THEN


s ← (a + b + c) / 2
area_triangle ← SQRT(s * (s - a) * (s - b) * (s - c))
perimeter_triangle ← a + b + c
PRINT "Triangle Area = ", area_triangle
PRINT "Triangle Perimeter = ", perimeter_triangle
ELSE
PRINT "Invalid triangle sides"

EXCEPT
PRINT "Invalid input! Please enter numeric values only."

FINALLY
PRINT "Program execution completed."
END

Page | 46
Source Code
#Python program to demonstrate Polymorphism in python

import math

# Base class
class Shape:
def area(self):
raise NotImplementedError("Subclass must implement area()
method")

def perimeter(self):
raise NotImplementedError("Subclass must implement
perimeter() method")

# Circle subclass
class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return [Link] * [Link] ** 2

def perimeter(self):
return 2 * [Link] * [Link]

# Square subclass
class Square(Shape):
def __init__(self, side):
[Link] = side

def area(self):
return [Link] ** 2

def perimeter(self):
return 4 * [Link]

# Triangle subclass (general triangle using Heron’s formula)


class Triangle(Shape):
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c

Page | 47
def area(self):
s = (self.a + self.b + self.c) / 2 # semi-perimeter
return [Link](s * (s - self.a) * (s - self.b) * (s -
self.c))

def perimeter(self):
return self.a + self.b + self.c

# -------- Main Program --------


print("Shape Calculations Program")

try:
# Circle input
r = float(input("\nEnter radius of Circle: "))
circle = Circle(r)
print("Circle - Area:", round([Link](), 2))
print("Circle - Perimeter:", round([Link](), 2))

# Square input
s_side = float(input("\nEnter side of Square: "))
square = Square(s_side)
print("Square - Area:", [Link]())
print("Square - Perimeter:", [Link]())

# Triangle input
a = float(input("\nEnter side a of Triangle: "))
b = float(input("Enter side b of Triangle: "))
c_side = float(input("Enter side c of Triangle: "))

# Triangle validity check


if (a + b > c_side) and (a + c_side > b) and (b + c_side >
a):
triangle = Triangle(a, b, c_side)
print("Triangle - Area:", round([Link](), 2))
print("Triangle - Perimeter:", [Link]())
else:
print("Invalid triangle sides! The sum of any two sides
must be greater than the third.")

except ValueError:
print("Invalid input! Please enter numeric values only.")

finally:
print("\nProgram execution completed.")

Page | 48
Output
E:\College\BTech>py [Link]
Shape Calculations Program

Enter radius of Circle: 3


Circle - Area: 28.27
Circle - Perimeter: 18.85

Enter side of Square: 6


Square - Area: 36.0
Square - Perimeter: 24.0

Enter side a of Triangle: 3


Enter side b of Triangle: 4
Enter side c of Triangle: 5
Triangle - Area: 6.0
Triangle - Perimeter: 12.0

Program execution completed.

Page | 49
Exercise 13. Python program to check whether a JSON string contains
complex object or not.
Aim: To check whether a JSON string contains complex object or not

Algorithm
Start
Read the JSON string from the user (or test case).
Try to parse the JSON string using [Link]().
• If parsing fails, print "Invalid JSON string" and return False.
Define a recursive function check(obj) to detect complex objects:
• If obj is a dictionary:
o Return True if dictionary is not empty.
o Otherwise, check each value inside the dictionary
recursively.
• If obj is a list:
o Return True if list is not empty.
o Otherwise, check each element in the list recursively.
• Otherwise (string, number, boolean, null): return False.
Call check(data) on the parsed JSON object.
Return the result (True/False).
Stop

Source Code
#check whether a JSON string contains complex object or
not.
import json

def contains_complex_object(json_string):
try:
# Parse JSON string
data = [Link](json_string)

# Recursive function to check for complex


objects
def is_complex(obj):
if isinstance(obj, (dict, list)):
return True # Found a complex object
return False

Page | 50
# detect complex objects
def check(obj):
if isinstance(obj, dict):
return True if obj else False or
any(check(v) for v in [Link]())
elif isinstance(obj, list):
return True if obj else False or
any(check(i) for i in obj)
return False

return check(data)

except [Link]:
print("Invalid JSON string")
return False

# --------- Test Cases ----------


json1 = '{"name": "Ravi", "age": 25}' # simple object
json2 = '{"user": {"name": "Rahul", "city":
"Chittoor"}}' # nested (complex)
json3 = '42' # just a number
json4 = '[1, 2, 3, {"a": 10}]' #list with complex object

print("JSON1:", contains_complex_object(json1))
print("JSON2:", contains_complex_object(json2))
print("JSON3:", contains_complex_object(json3))
print("JSON4:", contains_complex_object(json4))

Output
E:\College\BTech>py Check_JsonObject.py
JSON1: True
JSON2: True
JSON3: False
JSON4: True

Page | 51
Exercise 14. Python program to demonstrate use of ndim, shape, size,
dtype.
Aim: To demonstrate Numpy array attributes (ndim, shape size and dtype)

Algorithm
Start
1. For 1D Array:
o Prompt user to enter space-separated elements.
o Convert input to a list of integers.
o Create a NumPy array arr1 using [Link]().
o Print array and its properties:
▪ Number of dimensions (ndim), Shape (shape), Size (size)
▪ Data type (dtype)
2. For 2D Array:
o Prompt user to enter rows × cols elements.
o Convert input to a list of integers.
o Reshape into (rows, cols) and create array arr2.
o Print array and its properties.
3. For 3D Array:
o Prompt user to enter d1 × d2 × d3 elements.
o Convert input to a list of integers.
o Reshape into (d1, d2, d3) and create array arr3.
o Print array and its properties.
Stop

Page | 52
Source Code
# Demonstrate Numpy Attributes ndim, shape size and dtype
import numpy as np

# --- 1D Array ---


arr1 = [Link](list(map(int, input("Enter elements for
1D array (space-separated): ").split())))
print("\n1D Array:")
print(arr1)
print("ndim:", [Link])
print("shape:", [Link])
print("size:", [Link])
print("dtype:", [Link])

print("\n-------------------------\n")

# --- 2D Array ---


rows = int(input("Enter number of rows for 2D array: "))
cols = int(input("Enter number of columns for 2D array:
"))
print(f"Enter {rows*cols} elements for 2D array (space-
separated):")
elements_2d = list(map(int, input().split()))
arr2 = [Link](elements_2d).reshape(rows, cols)
print("\n2D Array:")
print(arr2)
print("ndim:", [Link])
print("shape:", [Link])
print("size:", [Link])
print("dtype:", [Link])

print("\n-------------------------\n")

# --- 3D Array ---


d1 = int(input("Enter dimension 1 size for 3D array: "))
d2 = int(input("Enter dimension 2 size for 3D array: "))
d3 = int(input("Enter dimension 3 size for 3D array: "))
print(f"Enter {d1*d2*d3} elements for 3D array (space-
separated):")
elements_3d = list(map(int, input().split()))

Page | 53
arr3 = [Link](elements_3d).reshape(d1, d2, d3)
print("\n3D Array:")
print(arr3)
print("ndim:", [Link])
print("shape:", [Link])
print("size:", [Link])
print("dtype:", [Link])

Page | 54
Output
E:\College\BTech>py Demo_Numpy_Attributes.py
Enter elements for 1D array (space-separated): 1 2 3 4 5

1D Array:
[1 2 3 4 5]
ndim: 1
shape: (5,)
size: 5
dtype: int64

Enter number of rows for 2D array: 2


Enter number of columns for 2D array: 3
Enter 6 elements for 2D array (space-separated):
15 25 30 25 30 40

2D Array:
[[15 25 30]
[25 30 40]]
ndim: 2
shape: (2, 3)
size: 6
dtype: int64

Enter dimension 1 size for 3D array: 2


Enter dimension 2 size for 3D array: 2
Enter dimension 3 size for 3D array: 2
Enter 8 elements for 3D array (space-separated):
10 15 20 30 48 15 25 35

3D Array:
[[[10 15]
[20 30]]

[[48 15]
[25 35]]]
ndim: 3
shape: (2, 2, 2)
size: 8
dtype: int64

Page | 55
Exercise 15. Select any two columns from the above data frame, and
observe the change in one attribute with respect to other attribute
with scatter and plot operations in matplotlib
Aim: To plot a scatter graph use any two columns using the above dataframe
Algorithm
Start
1. Import required libraries: pandas and [Link].
2. Define a list of keys → ["ID", "Name", "Age", "Marks", "City"].
3. Initialize an empty dictionary data.
4. For each key in keys:
1. Initialize an empty list values.
2. Display message: "Enter 10 values for " + key.
3. For i = 1 to 10:
▪ Prompt user to enter "key value i".
▪ If the key is ID, Age, or Marks:
▪ Try converting input to integer.
▪ If conversion fails, display error and assign 0.
▪ Append the value to values.
4. Store the list in dictionary → data[key] = values.
5. Convert dictionary data into a Pandas DataFrame df.
6. Display the DataFrame.
7. Display available columns from df.
8. Ask the user to choose two column names (col1 for X-axis, col2 for Y-axis).
9. Check if both columns exist in DataFrame:
o If valid:

Page | 56
▪ Assign x = df[col1], y = df[col2].
▪ Scatter Plot: Plot x vs y using [Link]().
▪ Line Plot: Plot x vs y using [Link]().
o Else: Print error message "Invalid column names entered!".
[Link] exceptions with try-except (to catch invalid inputs).
[Link] display "Program execution completed " in the finally block.
End

Page | 57
Source Code:
# plot the graph for the Dataframe
import pandas as pd
import [Link] as plt

# Create dictionary
data = {}
keys = ["ID", "Name", "Age", "Marks", "City"]

try:
for key in keys:
values = []
print("\nEnter 10 values for " + key + ":")
for i in range(10):
val = input("Enter " + key + " value " +
str(i+1) + ": ")

# Convert numeric fields to int safely


if key in ["ID", "Age", "Marks"]:
try:
val = int(val)
except ValueError:
print("Invalid input for " + key +
", setting default value 0")
val = 0
[Link](val)

data[key] = values

# Convert dictionary into DataFrame


df = [Link](data)
print("\nDataFrame:\n", df)

Page | 58
# choose two columns for plotting
print("\nAvailable columns:", list([Link]))
col1 = input("Enter first column for X-axis: ")
col2 = input("Enter second column for Y-axis: ")

if col1 in [Link] and col2 in [Link]:


x = df[col1]
y = df[col2]

# Scatter Plot
[Link](x, y, color="blue", marker="o")
[Link]("Scatter Plot: " + col1 + " vs " +
col2)
[Link](col1)
[Link](col2)
[Link](True)
[Link]()

# Step 5: Line Plot


[Link](x, y, color="green", marker="s",
linestyle="-")
[Link]("Line Plot: " + col1 + " vs " + col2)
[Link](col1)
[Link](col2)
[Link](True)
[Link]()
else:
print("\nInvalid column names entered!")

except Exception as e:
print("\nAn error occurred:", e)

finally:
print("\nProgram execution completed")

Page | 59
Output

E:\College\BTech>py DataFrame_PlotGraph.py

Enter 10 values for ID:


Enter ID value 1: 101
Enter ID value 2: 102
Enter ID value 3: 103
Enter ID value 4: 201
Enter ID value 5: 202
Enter ID value 6: 203
Enter ID value 7: 301
Enter ID value 8: 302
Enter ID value 9: 303
Enter ID value 10: 401

Enter 10 values for Name:


Enter Name value 1: Ramu
Enter Name value 2: Ravi
Enter Name value 3: Akbar
Enter Name value 4: Ankit
Enter Name value 5: Charan
Enter Name value 6: Chetak
Enter Name value 7: Daniel
Enter Name value 8: Surya
Enter Name value 9: Prakash
Enter Name value 10: Somu

Enter 10 values for Age:


Enter Age value 1: 25
Enter Age value 2: 23
Enter Age value 3: 22
Enter Age value 4: 21
Enter Age value 5: 18
Enter Age value 6: 24
Enter Age value 7: 23
Enter Age value 8: 22
Enter Age value 9: 18
Enter Age value 10: 19

Page | 60
Enter 10 values for Marks:
Enter Marks value 1: 85
Enter Marks value 2: 82
Enter Marks value 3: 83
Enter Marks value 4: 84
Enter Marks value 5: 82
Enter Marks value 6: 15
Enter Marks value 7: 18
Enter Marks value 8: 22
Enter Marks value 9: 55
Enter Marks value 10: 35

Enter 10 values for City:


Enter City value 1: Ahmedabad
Enter City value 2: Aurangabad
Enter City value 3: Chittoor
Enter City value 4: Tirupati
Enter City value 5: Madanapalli
Enter City value 6: Kuppam
Enter City value 7: Nellore
Enter City value 8: Ongole
Enter City value 9: Vijaywada
Enter City value 10: Guntur

DataFrame:
ID Name Age Marks City
0 101 Ramu 25 85 Ahmedabad
1 102 Ravi 23 82 Aurangabad
2 103 Akbar 22 83 Chittoor
3 201 Ankit 21 84 Tirupati
4 202 Charan 18 82 Madanapalli
5 203 Chetak 24 15 Kuppam
6 301 Daniel 23 18 Nellore
7 302 Surya 22 22 Ongole
8 303 Prakash 18 55 Vijaywada
9 401 Somu 19 35 Guntur

Page | 61
Available columns: ['ID', 'Name', 'Age', 'Marks',
'City']

Enter first column for X-axis: Age


Enter second column for Y-axis: Marks

Output

Page | 62

You might also like