0% found this document useful (0 votes)
3 views23 pages

Python Lab

Uploaded by

sree.devnova
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views23 pages

Python Lab

Uploaded by

sree.devnova
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

PYTHON PROGRAMMING

(SKILL ENHANCEMENT COURSE)


UNTI-I:
History of Python Programming Language, Thrust Areas of Python, Installing Anaconda Python
Distribution, Installing and Using Jupyter Notebook. Parts of Python Programming Language: Identifiers,
Keywords, Statements and Expressions, Variables, Operators, Precedence and Associativity, Data Types,
Indentation, Comments, Reading Input, Print Output, Type Conversions, the type () Function and Is
Operator, Dynamic and Strongly Typed Language. Control Flow Statements: if statement, if-else statement,
if...elif…else, Nested if statement, while Loop, for Loop, continue and break Statements, Catching
Exceptions Using try and except Statement.
Sample Experiments:
1. Write a program to find the largest element among three Numbers.
2. Write a Program to display all prime numbers within an interval
3. Write a program to swap two numbers without using a temporary variable.
4. 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
iii) Identity Operators
5. Write a program to add and multiply complex numbers 6. Write a program to print multiplication table
of a given number.

UNIT-II:
Functions: Built-In Functions, Commonly Used Modules, Function Definition and Calling the function,
return Statement and void Function, Scope and Lifetime of Variables, Default Parameters, Keyword
Arguments, *args and **kwargs, Command Line Arguments. Strings: Creating and Storing Strings, Basic
String Operations, Accessing Characters in String by Index Number, String Slicing and Joining, String
Methods, Formatting Strings. Lists: Creating Lists, Basic List Operations, Indexing and Slicing in Lists, Built-In
Functions Used on Lists, List Methods, del Statement.
Sample Experiments:
1. Write a program to define a function with multiple return values.
2. Write a program to define a function using default arguments.
3. Write a program to find the length of the string without using any library functions.
4. Write a program to check if the substring is present in a given string or not.
5. Write a program to perform the given operations on a list:
i. addition ii. Insertion iii. slicing
6. Write a program to perform any 5 built-in functions by taking any list.

UNIT-III:
Dictionaries: Creating Dictionary, Accessing and Modifying key:value Pairs in Dictionaries, Built-In
Functions Used on Dictionaries, Dictionary Methods, del Statement. Tuples and Sets: Creating Tuples, Basic
Tuple Operations, tuple() Function, Indexing and Slicing in Tuples, Built-In Functions Used on Tuples,
Relation between Tuples and Lists, Relation between Tuples and Dictionaries, Using zip() Function, Sets, Set
Methods, Frozenset.
Sample Experiments:
1. Write a program to create tuples (name, age, address, college) for at least two members and
concatenate the tuples and print the concatenated tuples.
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
[Link] a program to count the number of vowels in a string (No control flow allowed).
[Link] a program to check if a given key exists in a dictionary or not.
[Link] a program to add a new key-value pair to an existing dictionary.
[Link] a program to sum all the items in a given dictionary.

UNIT-IV:
Files: Types of Files, Creating and Reading Text Data, File Methods to Read and Write Data, Reading and
Writing Binary Files, Pickle Module, Reading and Writing CSV Files, Python os and [Link] Modules. Object-
Oriented Programming: Classes and Objects, Creating Classes in Python, Creating Objects in Python,
Constructor Method, Classes with Multiple Objects, Class Attributes Vs Data Attributes, Encapsulation,
Inheritance, Polymorphism.
Sample Experiments:
1. 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.
2. Python program to print each line of a file in reverse order.
3. Python program to compute the number of characters, words and lines in a file.
4. Write a program to create, display, append, insert and reverse the order of the items in the array.
5. Write a program to add, transpose and multiply two matrices.
6. Write a Python program to create a class that represents a shape. Include methods to find areas.

UNIT-V:
Introduction to Data Science: Functional Programming, JSON and XML in Python, NumPy with Python,
Pandas.
Sample Experiments:
1. Python program to check whether a JSON string contains complex object or not.
2. Python Program to demonstrate NumPy arrays creation using array () function.
3. Python program to demonstrate use of ndim, shape, size, dtype.
4. Python program to demonstrate basic slicing, integer and Boolean indexing.
5. Python program to find min, max, sum, cumulative sum of array
6. 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:
a) Apply head () function to the pandas data frame
b) Perform various data selection operations on Data Frame
7. 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
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
EXPERIMENTS
1) Write a program to find the largest element among three Numbers.
2) Write a Program to display all prime numbers within an interval
3) Write a program to swap two numbers without using a temporary variable.
4) 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 Operatorsv
iii) Identity Operators
5) Write a program to add and multiply complex numbers
6) Write a program to print multiplication table of a given number.
7) Write a program to define a function with multiple return values.
8) Write a program to define a function using default arguments.
9) Write a program to find the length of the string without using any library functions.
10) Write a program to check if the substring is present in a given string or not.
11) Write a program to perform the given operations on a list:
i. addition ii. Insertion iii. slicing
12) Write a program to perform any 5 built-in functions by taking any list.
13) Write a program to create tuples (name, age, address, college) for at least two members and
concatenate the tuples and print the concatenated tuples.
14) Write a program to count the number of vowels in a string (No control flow allowed).
15) Write a program to check if a given key exists in a dictionary or not.
16) Write a program to add a new key-value pair to an existing dictionary.
17) Write a program to sum all the items in a given dictionary.
18) 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.
19) Python program to print each line of a file in reverse order.
20) Python program to compute the number of characters, words and lines in a file.
21) Write a program to create, display, append, insert and reverse the order of the items in the array.
22) Write a program to add, transpose and multiply two matrices.
23) Write a Python program to create a class that represents a shape. Include methods to
24) Python program to check whether a JSON string contains complex object or not.
25) Python Program to demonstrate NumPy arrays creation using array () function.
26) Python program to demonstrate use of ndim, shape, size, dtype.
27) Python program to demonstrate basic slicing, integer and Boolean indexing.
28) Python program to find min, max, sum, cumulative sum of array
29) 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:
a) Apply head () function to the pandas data frame
b) Perform various data selection operations on Data Frame
30) 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
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
EXP1. Write a program to find the largest element among three Numbers.
# Program to find the largest among three numbers
# Taking input from the user
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))

# Compare the numbers


if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3

# Display the result


print("The largest number is:", largest)
OUTPUT
Enter first number: 25
Enter second number: 42
Enter third number: 18
The largest number is: 42.0

EXP2: Write a Program to display all prime numbers within an interval


# Function to check if a number is prime
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True

# Input from user


start = int(input("Enter the start of the interval: "))
end = int(input("Enter the end of the interval: "))

print(f"Prime numbers between {start} and {end} are:")

for num in range(start, end + 1):


if is_prime(num):
print(num, end=' ')
OUTPUT:
Enter the start of the interval: 10
Enter the end of the interval: 30
Prime numbers between 10 and 30 are:
11 13 17 19 23 29

EXP3: Write a program to swap two numbers without using a temporary variable.
# Input from user
a = int(input("Enter first number (a): "))
b = int(input("Enter second number (b): "))
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
print(f"Before swapping: a = {a}, b = {b}")

# Swapping using arithmetic operators


a=a+b
b=a-b
a=a-b

print(f"After swapping: a = {a}, b = {b}")


OUTPUT:
Enter first number (a): 5
Enter second number (b): 10
Before swapping: a = 5, b = 10
After swapping: a = 10, b = 5

EXP-4: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 Operatorsv
iii) Identity Operators
print("I) Arithmetic Operators")
a = 10
b=3
print(f"a + b = {a + b}") # Addition
print(f"a - b = {a - b}") # Subtraction
print(f"a * b = {a * b}") # Multiplication
print(f"a / b = {a / b}") # Division
print(f"a % b = {a % b}") # Modulus
print(f"a ** b = {a ** b}") # Exponentiation
print(f"a // b = {a // b}") # Floor Division

print("\nII) Relational Operators")


print(f"a == b: {a == b}") # Equal
print(f"a != b: {a != b}") # Not Equal
print(f"a > b: {a > b}") # Greater than
print(f"a < b: {a < b}") # Less than
print(f"a >= b: {a >= b}") # Greater than or equal
print(f"a <= b: {a <= b}") # Less than or equal

print("\nIII) Assignment Operators")


x=5
print(f"x = {x}")
x += 2
print(f"x += 2: {x}")
x -= 1
print(f"x -= 1: {x}")
x *= 3
print(f"x *= 3: {x}")
x /= 2
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
print(f"x /= 2: {x}")
x %= 4
print(f"x %= 4: {x}")

print("\nIV) Logical Operators")


p = True
q = False
print(f"p and q: {p and q}")
print(f"p or q: {p or q}")
print(f"not p: {not p}")

print("\nV) Bitwise Operators")


a = 5 # 0101
b = 3 # 0011
print(f"a & b: {a & b}") # AND
print(f"a | b: {a | b}") # OR
print(f"a ^ b: {a ^ b}") # XOR
print(f"~a: {~a}") # NOT
print(f"a << 1: {a << 1}") # Left Shift
print(f"a >> 1: {a >> 1}") # Right Shift

print("\nVI) Ternary Operator")


x = 10
y = 20
max_val = x if x > y else y
print(f"The maximum of {x} and {y} is {max_val}")

print("\nVII) Membership Operators")


nums = [1, 2, 3, 4, 5]
print(f"3 in nums: {3 in nums}")
print(f"10 not in nums: {10 not in nums}")

print("\nVIII) Identity Operators")


a = [1, 2, 3]
b=a
c = [1, 2, 3]
print(f"a is b: {a is b}") # True, same object
print(f"a is c: {a is c}") # False, different object with same content
print(f"a == c: {a == c}") # True, values are equal
OUTPUT:
I) Arithmetic Operators
a + b = 13
a-b=7
a * b = 30
a / b = 3.3333333333333335
a%b=1
a ** b = 1000
a // b = 3

II) Relational Operators


a == b: False
a != b: True
a > b: True
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
a < b: False
a >= b: True
a <= b: False

III) Assignment Operators


x=5
x += 2: 7
x -= 1: 6
x *= 3: 18
x /= 2: 9.0
x %= 4: 1.0

IV) Logical Operators


p and q: False
p or q: True
not p: False

V) Bitwise Operators
a & b: 1
a | b: 7
a ^ b: 6
~a: -6
a << 1: 10
a >> 1: 2

VI) Ternary Operator


The maximum of 10 and 20 is 20

VII) Membership Operators


3 in nums: True
10 not in nums: True

VIII) Identity Operators


a is b: True
a is c: False
a == c: True

EXP-5 Write a program to add and multiply complex numbers


# Input complex numbers
c1 = complex(input("Enter the first complex number (e.g., 2+3j): "))
c2 = complex(input("Enter the second complex number (e.g., 4+5j): "))

# Addition of complex numbers


sum_result = c1 + c2

# Multiplication of complex numbers


product_result = c1 * c2

# Output the results


print(f"\nFirst Complex Number: {c1}")
print(f"Second Complex Number: {c2}")
print(f"Sum: {sum_result}")
print(f"Product: {product_result}")
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
OUTPUT:
Enter the first complex number (e.g., 2+3j): 2+3j
Enter the second complex number (e.g., 4+5j): 4+5j

First Complex Number: (2+3j)


Second Complex Number: (4+5j)
Sum: (6+8j)
Product: (-7+22j)

EXP-6 Write a program to print multiplication table of a given number.


# Input from the user
num = int(input("Enter a number to print its multiplication table: "))

# Print the table


print(f"\nMultiplication Table of {num}:")
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")

OUTPUT:
Enter a number to print its multiplication table: 7
Multiplication Table of 7:
7x1=7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

EXP-7 Write a program to define a function with multiple return values.


# Function to return sum and product of two numbers
def compute(a, b):
sum_result = a + b
product_result = a * b
return sum_result, product_result # returning multiple values as a tuple

# Input from user


x = int(input("Enter first number: "))
y = int(input("Enter second number: "))

# Call the function and store the results


sum_val, prod_val = compute(x, y)

# Output the results


print(f"Sum = {sum_val}")
print(f"Product = {prod_val}")
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
OUTPUT:
Enter first number: 4
Enter second number: 5
Sum = 9
Product = 20

EXP-8:Write a program to define a function using default arguments.


# Function with default argument
def greet(name="Guest"):
print(f"Hello, {name}! Welcome to Python programming.")

# Calling the function without an argument


greet()

# Calling the function with an argument


greet("CSE 3RD YEAR STUDENTS")
OUTPUT:
Hello, Guest! Welcome to Python programming.
Hello, CSE 3RD YEAR STUDENTS! Welcome to Python programming.

EXP-9:Write a program to find the length of the string without using any library functions.
# Input string from the user
text = input("Enter a string: ")
# Initialize counter
count = 0

# Loop through each character in the string


for char in text:
count += 1

# Output the length


print(f"The length of the string is: {count}")
OUTPUT:
Enter a string: Hello World
The length of the string is: 11

EXP-10:Write a program to check if the substring is present in a given string or not.


# Input main string and substring from the user
main_str = input("Enter the main string: ")
sub_str = input("Enter the substring to search: ")

# Check for substring


if sub_str in main_str:
print(f"Yes, '{sub_str}' is present in the given string.")
else:
print(f"No, '{sub_str}' is not present in the given string.")
OUTPUT:
Enter the main string: Hello, how are you?
Enter the substring to search: how
Yes, 'how' is present in the given string.
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
EXP-11:Write a program to perform the given operations on a list:
i. addition ii. Insertion iii. slicing
# Initial list
my_list = [10, 20, 30, 40, 50]
print("Original list:", my_list)

# i. Addition (concatenation)
add_list = [60, 70]
my_list += add_list
print("After addition:", my_list)

# ii. Insertion
my_list.insert(2, 25) # Insert 25 at index 2
print("After insertion at index 2:", my_list)

# iii. Slicing
sliced_list = my_list[2:6] # Get elements from index 2 to 5
print("Sliced list (index 2 to 5):", sliced_list)
OUTPUT:
Original list: [10, 20, 30, 40, 50]
After addition: [10, 20, 30, 40, 50, 60, 70]
After insertion at index 2: [10, 20, 25, 30, 40, 50, 60, 70]
Sliced list (index 2 to 5): [25, 30, 40, 50]

EXP-12:Write a program to perform any 5 built-in functions by taking any list.


# Sample list
numbers = [10, 5, 8, 20, 3]

print("Original list:", numbers)

# 1. len() – Get the length of the list


print("Length of the list:", len(numbers))

# 2. max() – Find the maximum value


print("Maximum value in the list:", max(numbers))

# 3. min() – Find the minimum value


print("Minimum value in the list:", min(numbers))

# 4. sum() – Calculate the sum of all elements


print("Sum of all elements:", sum(numbers))

# 5. sorted() – Return a new sorted list


sorted_list = sorted(numbers)
print("Sorted list (ascending):", sorted_list)
OUTPUT:
Original list: [10, 5, 8, 20, 3]
Length of the list: 5
Maximum value in the list: 20
Minimum value in the list: 3
Sum of all elements: 46
Sorted list (ascending): [3, 5, 8, 10, 20]
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
EXP-13:Write a program to create tuples (name, age, address, college) for at least two members and
concatenate the tuples and print the concatenated tuples.
# Creating tuples for two members
member1 = ("RAJA", 21, "Hyderabad", "ABC College")
member2 = ("Fatima", 22, "Chennai", "XYZ College")

# Concatenating the tuples


combined = member1 + member2

# Displaying the result


print("Tuple for Member 1:", member1)
print("Tuple for Member 2:", member2)
print("Concatenated Tuple:", combined)
OUTPUT:
Tuple for Member 1: ('RAJA', 21, 'Hyderabad', 'ABC College')
Tuple for Member 2: ('Fatima', 22, 'Chennai', 'XYZ College')
Concatenated Tuple: ('RAJA', 21, 'Hyderabad', 'ABC College', 'Fatima', 22, 'Chennai', 'XYZ College')

EXP-14:Write a program to count the number of vowels in a string (No control flow allowed).
# Input string from user
text = input("Enter a string: ")

# Convert to lowercase to simplify vowel matching


lower_text = [Link]()

# Count vowels using sum and comprehension (no if, for, or while loops)
vowel_count = sum(map(lower_text.count, "aeiou"))

# Output the result


print(f"Number of vowels: {vowel_count}")
OUTPUT:
Enter a string: Hello World
Number of vowels: 3

EXP-15:Write a program to check if a given key exists in a dictionary or not.


# Sample dictionary
student = {
"name": "ARYA",
"age": 21,
"college": "ABC College",
"course": "AI & DS"
}
# Input key to search
key_to_check = input("Enter the key to search in the dictionary: ")

# Check if key exists


if key_to_check in student:
print(f"Yes, the key '{key_to_check}' exists in the dictionary.")
print(f"Value:
OUTPUT:
Enter the key to search in the dictionary: age
Yes, the key 'age' exists in the dictionary.
Value: 21
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
EXP-16:Write a program to add a new key-value pair to an existing dictionary.
# Existing dictionary
student = {
"name": "ARYA",
"age": 21,
"college": "ABC Institute"
}

# New key-value pair to add


student["course"] = "AI & Data Science"

# Display updated dictionary


print("Updated Dictionary:")
print(student)
OUTPUT:
Updated Dictionary:
{'name': 'ARYA', 'age': 21, 'college': 'ABC Institute', 'course': 'AI & Data Science'}

EXP-17: Write a program to sum all the items in a given dictionary.


# Given dictionary
numbers = {
"a": 10,
"b": 20,
"c": 30,
"d": 40
}

# Sum all the values in the dictionary


total_sum = sum([Link]())

# Display the result


print("Sum of all items in the dictionary:", total_sum)
OUTPUT:
Sum of all items in the dictionary: 100

EXP-18: 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.
# Read from source file
with open('[Link]', 'r') as source_file:
text = source_file.read()

# Split text into words and convert to lowercase


words = [Link]().split()

# Sort the words


[Link]()

# Write the sorted words to destination file


with open('[Link]', 'w') as output_file:
for word in words:
output_file.write(word + '\n')

print("Words sorted and written to [Link] in lowercase.")


PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
OUTPUT:
If [Link] contains:
Hello world This is Python
Then [Link] will contain:
hello
is
python
this
World

EXP-19: Python program to print each line of a file in reverse order.


# Open and read the file line by line
with open('[Link]', 'r') as file:
lines = [Link]()

# Print each line in reverse order (characters reversed)


for line in lines:
print([Link]()[::-1])
OUTPUT:
If [Link] contains:
Hello World
Python is fun
Then [Link] will contain:
dlroW olleH
nuf si nohtyP

EXP-20: Python program to compute the number of characters, words and lines in a file.
# Open the file in read mode
with open('[Link]', 'r') as file:
text = [Link]()

# Count lines
with open('[Link]', 'r') as file:
lines = [Link]()

num_lines = len(lines)
num_words = len([Link]())
num_characters = len(text)

# Display results
print("Number of lines:", num_lines)
print("Number of words:", num_words)
print("Number of characters:", num_characters)
OUTPUT:
If [Link] contains:
Hello World
Python is fun
THEN OUTPUT WILL BE:
Number of lines: 2
Number of words: 5
Number of characters: 26
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
EXP-21: Write a program to create, display, append, insert and reverse the order of the items in the
array.
import array
# 1. Create an array of integers
arr = [Link]('i', [10, 20, 30, 40, 50])
print("Original array:", arr)

# 2. Append an item
[Link](60)
print("After appending 60:", arr)

# 3. Insert an item at position 2


[Link](2, 25)
print("After inserting 25 at index 2:", arr)

# 4. Reverse the array


[Link]()
print("After reversing:", arr)
OUTPUT:
Original array: array('i', [10, 20, 30, 40, 50])
After appending 60: array('i', [10, 20, 30, 40, 50, 60])
After inserting 25 at index 2: array('i', [10, 20, 25, 30, 40, 50, 60])
After reversing: array('i', [60, 50, 40, 30, 25, 20, 10])

EXP-22: Write a program to add, transpose and multiply two matrices.


# Define two 2x2 matrices
A = [[1, 2],
[3, 4]]

B = [[5, 6],
[7, 8]]

# 1. Matrix Addition
def add_matrices(A, B):
result = [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
return result

# 2. Matrix Transpose
def transpose_matrix(M):
result = [[M[j][i] for j in range(len(M))] for i in range(len(M[0]))]
return result

# 3. Matrix Multiplication
def multiply_matrices(A, B):
result = []
for i in range(len(A)):
row = []
for j in range(len(B[0])):
sum_product = 0
for k in range(len(B)):
sum_product += A[i][k] * B[k][j]
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
[Link](sum_product)
[Link](row)
return result

# Perform operations
add_result = add_matrices(A, B)
transpose_A = transpose_matrix(A)
multiply_result = multiply_matrices(A, B)

# Display results
print("Matrix A:")
for row in A:
print(row)

print("\nMatrix B:")
for row in B:
print(row)

print("\nAddition (A + B):")
for row in add_result:
print(row)

print("\nTranspose of A:")
for row in transpose_A:
print(row)

print("\nMultiplication (A x B):")
for row in multiply_result:
print(row)
OUTPUT:
Matrix A:
[1, 2]
[3, 4]

Matrix B:
[5, 6]
[7, 8]

Addition (A + B):
[6, 8]
[10, 12]

Transpose of A:
[1, 3]
[2, 4]

Multiplication (A x B):
[19, 22]
[43, 50]
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
EXP-23:Write a Python program to create a class that represents a shape. Include methods to
import math
# Base class
class Shape:
def __init__(self, name="Shape"):
[Link] = name

def area(self):
return 0

def perimeter(self):
return 0

def display(self):
print(f"{[Link]}:")
print(f" Area: {[Link]()}")
print(f" Perimeter: {[Link]()}\n")

# Derived class: Rectangle


class Rectangle(Shape):
def __init__(self, length, width):
super().__init__("Rectangle")
[Link] = length
[Link] = width

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

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

# Derived class: Circle


class Circle(Shape):
def __init__(self, radius):
super().__init__("Circle")
[Link] = radius

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

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

# Example usage
rect = Rectangle(5, 3)
circle = Circle(4)

[Link]()
[Link]()
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
OUTPUT:
Rectangle:
Area: 15
Perimeter: 16

Circle:
Area: 50.26548245743669
Perimeter: 25.132741228718345

EXP-24:Python program to check whether a JSON string contains complex object or not.
What is a “complex object” in JSON?
We usually refer to nested dictionaries, lists, or a dictionary inside a dictionary/list as complex. Simple
values would be just strings, numbers, booleans, etc.

import json

def is_complex(value):
"""Recursively checks if the value contains complex structures."""
if isinstance(value, dict):
# If any value in the dict is dict or list, it's complex
return any(isinstance(v, (dict, list)) or is_complex(v) for v in [Link]())
elif isinstance(value, list):
# If any item in list is dict or list, it's complex
return any(isinstance(item, (dict, list)) or is_complex(item) for item in value)
return False

# Sample JSON string #TRY WITH SIMPLER JSON


json_str = ''' json_str=’”
{ {
"name": "ARYA", "name":"ARYA",
"age": 21, "age": 21,
"address": { }
"city": "Hyderabad",
"zipcode": "500001"
},
"hobbies": ["coding", "reading"]
}
'''

# Convert JSON string to Python object


try:
data = [Link](json_str)
if is_complex(data):
print("The JSON contains complex objects.")
else:
print("The JSON does NOT contain complex objects.")
except [Link]:
print("Invalid JSON string.")
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
OUTPUT:1
The JSON contains complex objects.
OUTPUT:2
The JSON does NOT contain complex objects.

EXP-25: Python Program to demonstrate NumPy arrays creation using array () function
✅ Note: Make sure NumPy is installed. You can install it using:
import numpy as np
# 1. Create a 1D array
array1 = [Link]([10, 20, 30, 40])
print("1D Array:")
print(array1)

# 2. Create a 2D array
array2 = [Link]([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:")
print(array2)

# 3. Create a 3D array
array3 = [Link]([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("\n3D Array:")
print(array3)

# 4. Create array with mixed data types (NumPy will upcast to a common type)
array4 = [Link]([1, 2.5, 3])
print("\nArray with mixed data types:")
print(array4)
OUTPUT:
1D Array:
[10 20 30 40]

2D Array:
[[1 2 3]
[4 5 6]]

3D Array:
[[[1 2]
[3 4]]

[[5 6]
[7 8]]]

Array with mixed data types:


[1. 2.5 3. ]

EXP-26: Python program to demonstrate use of ndim, shape, size, dtype.


import numpy as np
# Create a NumPy array
arr = [Link]([[1, 2, 3], [4, 5, 6]])
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
# Display the array
print("Array:")
print(arr)

# Number of dimensions
print("\nNumber of dimensions (ndim):", [Link])

# Shape of the array


print("Shape of array (shape):", [Link])

# Total number of elements


print("Total elements in array (size):", [Link])

# Data type of elements


print("Data type of array elements (dtype):", [Link])
OUTPUT:
Array:
[[1 2 3]
[4 5 6]]

Number of dimensions (ndim): 2


Shape of array (shape): (2, 3)
Total elements in array (size): 6
Data type of array elements (dtype): int64 # (or int32 depending on your system)

EXP-27: Python program to demonstrate basic slicing, integer and Boolean indexing.
import numpy as np
# Create a 1D array
arr = [Link]([10, 20, 30, 40, 50, 60])

print("Original Array:")
print(arr)

# 1. Basic Slicing
print("\nBasic Slicing (arr[1:4]):")
print(arr[1:4]) # Output: [20, 30, 40]

# 2. Integer Indexing
indices = [0, 2, 4]
print("\nInteger Indexing (arr[[0, 2, 4]]):")
print(arr[indices]) # Output: [10, 30, 50]

# 3. Boolean Indexing
bool_index = arr > 30
print("\nBoolean Indexing (arr > 30):")
print("Boolean mask:", bool_index)
print("Filtered values:", arr[bool_index]) # Output: [40, 50, 60]
OUTPUT:
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
Original Array:
[10 20 30 40 50 60]

Basic Slicing (arr[1:4]):


[20 30 40]

Integer Indexing (arr[[0, 2, 4]]):


[10 30 50]

Boolean Indexing (arr > 30):


Boolean mask: [False False False True True True]
Filtered values: [40 50 60]

EXP-28: Python program to find min, max, sum, cumulative sum of array
import numpy as np
# Create a NumPy array
arr = [Link]([5, 10, 15, 20, 25])

print("Array:")
print(arr)

# Minimum value
print("\nMinimum value:", [Link](arr))

# Maximum value
print("Maximum value:", [Link](arr))

# Sum of all elements


print("Sum of array:", [Link](arr))

# Cumulative sum
print("Cumulative sum:", [Link](arr))
OUTPUT:
Array:
[ 5 10 15 20 25]

Minimum value: 5
Maximum value: 25
Sum of array: 75
Cumulative sum: [ 5 15 30 50 75]

EXP-29: 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:
a) Apply head () function to the pandas data frame
b) Perform various data selection operations on Data Frame
import pandas as pd
# Step 1: Create a dictionary with lists
data = {
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
"Name": ["Althaf", "Ravi", "Priya", "John", "Sara", "Meena", "Ajay", "Nina", "Vijay", "Kiran"],
"Age": [21, 22, 20, 23, 24, 22, 21, 23, 25, 20],
"Department": ["CSE", "ECE", "EEE", "MECH", "CSE", "IT", "CSE", "IT", "ECE", "EEE"],
"Marks": [85, 78, 92, 70, 88, 90, 76, 84, 69, 95],
"City": ["Hyderabad", "Delhi", "Mumbai", "Chennai", "Bangalore", "Hyderabad", "Delhi", "Mumbai",
"Chennai", "Bangalore"]
}

# Step 2: Convert dictionary to DataFrame


df = [Link](data)

# Step 3a: Use head() to show first 5 rows


print("First 5 rows using head():")
print([Link]())

# Step 3b: Data selection operations


print("\nSelect 'Name' and 'Marks' columns:")
print(df[["Name", "Marks"]])

print("\nSelect rows where Marks > 80:")


print(df[df["Marks"] > 80])

print("\nSelect rows where Department is 'CSE':")


print(df[df["Department"] == "CSE"])

print("\nSelect rows 2 to 5 using iloc:")


print([Link][2:6])

print("\nSelect row with index 3 using loc:")


print([Link][3])
OUTPUT:
First 5 rows using head():
Name Age Department Marks City
0 Althaf 21 CSE 85 Hyderabad
1 Ravi 22 ECE 78 Delhi
2 Priya 20 EEE 92 Mumbai
3 John 23 MECH 70 Chennai
4 Sara 24 CSE 88 Bangalore

Select 'Name' and 'Marks' columns:


Name Marks
0 Althaf 85
1 Ravi 78
2 Priya 92
...

Select rows where Marks > 80:


Name Age Department Marks City
0 Althaf 21 CSE 85 Hyderabad
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
2 Priya 20 EEE 92 Mumbai
...

Select rows where Department is 'CSE':


Name Age Department Marks City
0 Althaf 21 CSE 85 Hyderabad
4 Sara 24 CSE 88 Bangalore
6 Ajay 21 CSE 76 Delhi

Select rows 2 to 5 using iloc:


Name Age Department Marks City
2 Priya 20 EEE 92 Mumbai
3 John 23 MECH 70 Chennai
4 Sara 24 CSE 88 Bangalore
5 Meena 22 IT 90 Hyderabad

Select row with index 3 using loc:


Name John
Age 23
Department MECH
Marks 70
City Chennai
Name: 3, dtype: object

EXP-30: 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
import pandas as pd
import [Link] as plt

# Reusing the same DataFrame


data = {
"Name": ["Althaf", "Ravi", "Priya", "John", "Sara", "Meena", "Ajay", "Nina", "Vijay", "Kiran"],
"Age": [21, 22, 20, 23, 24, 22, 21, 23, 25, 20],
"Department": ["CSE", "ECE", "EEE", "MECH", "CSE", "IT", "CSE", "IT", "ECE", "EEE"],
"Marks": [85, 78, 92, 70, 88, 90, 76, 84, 69, 95],
"City": ["Hyderabad", "Delhi", "Mumbai", "Chennai", "Bangalore", "Hyderabad", "Delhi", "Mumbai",
"Chennai", "Bangalore"]
}

df = [Link](data)

# Select columns: Age vs Marks


ages = df['Age']
marks = df['Marks']

# SCATTER PLOT
[Link](figsize=(10, 4))
[Link](1, 2, 1)
[Link](ages, marks, color='blue', marker='o')
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)
[Link]("Scatter Plot: Age vs Marks")
[Link]("Age")
[Link]("Marks")
[Link](True)

# LINE PLOT
[Link](1, 2, 2)
[Link](ages, marks, color='green', marker='s', linestyle='-')
[Link]("Line Plot: Age vs Marks")
[Link]("Age")
[Link]("Marks")
[Link](True)

# Show plots
plt.tight_layout()
[Link]()

OUTPUT:
WHAT YOU WILL SEE :
· Scatter Plot: Shows how each student’s marks vary by age, as individual points.
· · Line Plot: Connects the age vs marks data to observe trends or patterns.

You might also like