Python Lab Exercises Record 2025
Python Lab Exercises Record 2025
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
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
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
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
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
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
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
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
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")
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")
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
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.
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 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
Algorithm
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: "))
# Ensure the lower bound is at least 2, as prime numbers must be greater than 1
if lower < 2:
lower = 2
# 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
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"
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
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 = []
except ValueError:
print("\nInvalid input! Please enter valid integers where
required.")
finally:
print("\nProgram execution completed.")
Page | 24
Output
List after addition: ['10', '5', '6', '2', '3', '8', '9', '4']
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")
Output
Concatenated Tuple:
('Ravi', 21, '2-45 Bazar Street', 'Chittoor', 'Raju', 22, '20-45
Gandi Road', 'Chittoor')
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: ")
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
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
#------------------------------------------------------
#Sort words
sorted_words = sorted(word)
print(sorted_words)
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")
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]
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
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]
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]
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.
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 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)
# 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")
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
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]
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
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: "))
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
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)
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
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
print("\n-------------------------\n")
print("\n-------------------------\n")
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
2D Array:
[[15 25 30]
[25 30 40]]
ndim: 2
shape: (2, 3)
size: 6
dtype: int64
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) + ": ")
data[key] = values
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: ")
# Scatter Plot
[Link](x, y, color="blue", marker="o")
[Link]("Scatter Plot: " + col1 + " vs " +
col2)
[Link](col1)
[Link](col2)
[Link](True)
[Link]()
except Exception as e:
print("\nAn error occurred:", e)
finally:
print("\nProgram execution completed")
Page | 59
Output
E:\College\BTech>py DataFrame_PlotGraph.py
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
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']
Output
Page | 62