0% found this document useful (0 votes)
22 views49 pages

Python Programming Lab Manual

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)
22 views49 pages

Python Programming Lab Manual

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

SREE VENKATESWARA

COLLEGE OF ENGINEERING
(AUTONOMOUS)
[Link], NELLORE (DIST)

AFFILIATED TO JNTU, ANANTAPUR.

PYTHON
PROGRAMMING LAB
MANUAL
(R- 23 REGULATION)
II BTECH CSE –I SEM

DEPARTMENT
OF
ARTIFICIAL INTELLIGENCE AND MACHINE
LEARNING
NAME OF THE STUDENT

ROLL NO

YEAR

BRANCH
SREE VENKATESWARA COLLEGE OF ENGINEERING
NAAC ‘A’ Grade Accredited
Institution An ISO 9001: 2015
Certified Institution
(Approved by AICTE, New Delhi and Affiliated to JNTU, Anantapur)
Northrajupalem (Vi), Kodavaluru (M) , S.P.S.R Nellore (Dt)-524316

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

Vision of the Institute

 Be a best institute to originate and foster skilled engineers and create


changemaker’s for the development of nation with a phenomenal
wisdom with morals, values and societal responsibilities.

Mission of the Institute

 M1: To impart graduate with quality education and use


innovative teaching-learning process to excel in their careers.
 M2: To build an ecosystem and play a vital role in
strengthening innovative research and entrepreneurship skills
among graduates.
 M3: To produce engineers with moral values and social
responsibility, and address societal needs for better nation.
SREE VENKATESWARA COLLEGE OF ENGINEERING
NAAC ‘A’ Grade Accredited
Institution An ISO 9001: 2015
Certified Institution
(Approved by AICTE, New Delhi and Affiliated to JNTU, Anantapur)
Northrajupalem (Vi), Kodavaluru (M) , S.P.S.R Nellore (Dt)-524316

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

Vision of the Department

 To produce the globally competent professionals in the field of


computer science and engineering with socio economic and ethical
values.

Mission of the Department

 M1: To provide state-of-the-art computer science and


engineering facilities through innovative teaching and learning
practices.
 M2: To prepare the graduates for higher learning, emphasizing
research and entrepreneurship.
 M3: To inculcate ethical values, leadership qualities, and
professional behaviour to improve the living standards of society. 
SREE VENKATESWARA COLLEGE OF ENGINEERING
NAAC ‘A’ Grade Accredited
Institution An ISO 9001:: 2015
Certified Institution
(Approved by AICTE, New Delhi and Affiliated to JNTU, Anantapur)
Northrajupalem (Vi), Kodavaluru (M) , S.P.S.R Nellore (Dt)-524316

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

Program Educational Objectives

PEO-1: To provide the graduates with effectively applying mathematics,


science, and engineering methodologies for analyzing, designing, and
implementing software solutions for real-world problems.

PEO-2: To become recognized professional engineers with a demonstrated


commitment to lifelong learning, continuous learning, and self-improvement
to change in computer science engineering.

PEO-3: To train the graduates to have basic interpersonal skills and a sense
of social responsibility that covers them a way to become good team members
and leaders.
SREE VENKATESWARA COLLEGE OF ENGINEERING
NAAC ‘A’ Grade Accredited
Institution An ISO 9001:: 2015
Certified Institution
(Approved by AICTE, New Delhi and Affiliated to JNTU, Anantapur)
Northrajupalem (Vi), Kodavaluru (M) , S.P.S.R Nellore (Dt)-524316

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

Program Outcomes (PO’s)

PO_1 Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering problems.
PO_2 Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO_3 Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for
the public health and safety, and the cultural, societal, and environmental
considerations.
PO_4 Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO_5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an understanding of the limitations.
PO_6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO_7 Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
PO_8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
PO_9 Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO_10 Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive
clear instructions.
PO_11 Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member and
leader in a team, to manage projects and in multidisciplinary environments.
PO_12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
SREE VENKATESWARA COLLEGE OF ENGINEERING
NAAC ‘A’ Grade Accredited
Institution An ISO 9001:: 2015
Certified Institution
(Approved by AICTE, New Delhi and Affiliated to JNTU, Anantapur)
Northrajupalem (Vi), Kodavaluru (M) , S.P.S.R Nellore (Dt)-524316

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND MACHINE LEARNING

Program Specific Outcomes (PSO’s)

PSO-1: Domain-specific knowledge: Acquire knowledge of hardware


functionality, design, and development of software components required to
process the information.

PSO-2: Problem-solving skills: Analyze data, identify data structures,


design suitable algorithms, develop and maintain software for real-world
problems.
INDEX
[Link]. Date Name of the Program Page Remarks
No.
PYTHON PROGRAMMING
(SKILL ENHANCEMENT COURSE)

UNIT-1

Program-1:

Aim: Write a program to find the largest element among three Numbers

Program:
# Function to find the largest of three numbers
def find_largest(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3
return largest
# Input three numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
# Find and print the largest number
largest = find_largest(num1, num2, num3)
print(f"The largest number among {num1}, {num2}, and {num3} is {largest}")

Output:
Program-2:

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

Program:
# Function to check if a number is prime
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
# Function to find all prime numbers in a given interval
def find_primes(start, end):
primes = []
for num in range(start, end + 1):
if is_prime(num):
[Link](num)
return primes
# Input the interval
start = int(input("Enter the starting number of the interval: "))
end = int(input("Enter the ending number of the interval: "))
# Find and print all prime numbers in the interval
primes = find_primes(start, end)
print(f"Prime numbers between {start} and {end} are: {primes}")

Output:
Program-3:

Aim: Write a program to swap two numbers without using a temporary variable

Program:
# Function to swap two numbers
def swap_numbers(a, b):
print(f"Before swapping: a = {a}, b = {b}")
a, b = b, a # Swapping using tuple unpacking
print(f"After swapping: a = {a}, b = {b}")
return a, b
# Input two numbers
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
# Swap and display the numbers
swap_numbers(a, b)

Output:
Program-4:

Aim: 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

Program:
def demonstrate_operators():
a = 10
b=3
c = None
print(f"Arithmetic Operators:")
print(f"Addition: {a} + {b} = {a + b}")
print(f"Subtraction: {a} - {b} = {a - b}")
print(f"Multiplication: {a} * {b} = {a * b}")
print(f"Division: {a} / {b} = {a / b}")
print(f"Modulus: {a} % {b} = {a % b}")
print(f"Exponentiation: {a} ** {b} = {a ** b}")
print(f"Floor Division: {a} // {b} = {a // b}")
print(f"Relational Operators:")
print(f"{a} > {b}: {a > b}")
print(f"{a} < {b}: {a < b}")
print(f"{a} == {b}: {a == b}")
print(f"{a} != {b}: {a != b}")
print(f"{a} >= {b}: {a >= b}")
print(f"{a} <= {b}: {a <= b}")
print(f"Assignment Operators:")
c=a+b
print(f"c = a + b: c = {c}")
c += a
print(f"c += a: c = {c}")
c -= a
print(f"c -= a: c = {c}")
c *= a
print(f"c *= a: c = {c}")
c /= a
print(f"c /= a: c = {c}")
c %= a
print(f"c %= a: c = {c}")
c **= b
print(f"c **= b: c = {c}")
c //= b
print(f"c //= b: c = {c}")
print(f"Logical Operators:")
print(f"a > 5 and b < 5: {a > 5 and b < 5}")
print(f"a > 5 or b > 5: {a > 5 or b > 5}")
print(f"not(a > 5): {not(a > 5)}")
print(f"Bitwise Operators:")
print(f"a = {a} ({bin(a)})")
print(f"b = {b} ({bin(b)})")
print(f"a & b: {a & b} ({bin(a & b)})")
print(f"a | b: {a | b} ({bin(a | b)})")
print(f"a ^ b: {a ^ b} ({bin(a ^ b)})")
print(f"~a: {~a} ({bin(~a)})")
print(f"a << 2: {a << 2} ({bin(a << 2)})")
print(f"a >> 2: {a >> 2} ({bin(a >> 2)})")
print(f"Ternary Operator:")
max_value = a if a > b else b
print(f"Max value between a and b: {max_value}")
print(f"Membership Operators:")
my_list = [1, 2, 3, 4, 5]
print(f"a in my_list: {a in my_list}")
print(f"b in my_list: {b in my_list}")
print(f"6 not in my_list: {6 not in my_list}")
print(f"Identity Operators:")
x=5
y=5
print(f"x is y: {x is y}")
print(f"x is not y: {x is not y}")
z = [1, 2, 3]
w = [1, 2, 3]
print(f"z is w: {z is w}")
print(f"z is not w: {z is not w}")
demonstrate_operators()

Output:
Program-5:
Aim: Write a program to add and multiply complex numbers

Program:
# Function to add two complex numbers
def add_complex_numbers(c1, c2):
return c1 + c2
# Function to multiply two complex numbers
def multiply_complex_numbers(c1, c2):
return c1 * c2
# Input two complex numbers
c1 = complex(input("Enter the first complex number (in the form a+bj): "))
c2 = complex(input("Enter the second complex number (in the form a+bj): "))
# Add and multiply the complex numbers
sum_result = add_complex_numbers(c1, c2)
product_result = multiply_complex_numbers(c1, c2)
# Display the results
print(f"The sum of {c1} and {c2} is {sum_result}")
print(f"The product of {c1} and {c2} is {product_result}")

Output:
Program-6:

Aim: Write a program to print multiplication table of a given number

Program:
# Function to print the multiplication table of a given number
def print_multiplication_table(number, up_to=10):
print(f"Multiplication Table for {number}:")
for i in range(1, up_to + 1):
print(f"{number} x {i} = {number * i}")
# Input the number for which the multiplication table is to be printed
number = int(input("Enter the number to print the multiplication table: "))
up_to = int(input("Enter the range up to which the multiplication table should be printed
(default is 10): ") or 10)
# Print the multiplication table
print_multiplication_table(number, up_to)

Output:
UNIT-2
Program-7:

Aim: Write a program to define a function with multiple return values.


Program:
# Function to return multiple values: sum, difference, and product
def calculate_operations(num1, num2):
sum_value = num1 + num2
difference = num1 - num2
product = num1 * num2
return sum_value, difference, product
# Input two numbers from the user
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
# Get the multiple return values from the function
sum_value, difference, product = calculate_operations(num1, num2)
# Print the results
print(f"The sum of {num1} and {num2} is: {sum_value}")
print(f"The difference between {num1} and {num2} is: {difference}")
print(f"The product of {num1} and {num2} is: {product}")

Output:
Program-8:

Aim: Write a program to define a function using default arguments.


Program:
def greet(name, greeting="Hello", punctuation="!"):
return f"{greeting}, {name}{punctuation}"
# Calling the function with only the required argument
print(greet("Alice")) # Output: Hello, Alice!
# Calling the function with one optional argument
print(greet("Bob", "Hi")) # Output: Hi, Bob!
# Calling the function with all arguments
print(greet("Charlie", "Good morning", ".")) # Output: Good morning, Charlie.

Output:
Program-9:

Aim: Write a program to find the length of the string without using any library functions.
Program:
def find_string_length(string):
"""Calculates the length of a string without using any library functions."""
count = 0
for char in string:
count += 1
return count
user_input = input("Enter a string: ")
length = find_string_length(user_input)
print("Length of the string:", length)

Output:
Program-10:

Aim: Write a program to check if the substring is present in a given string or not.
Program:
def is_substring_present(main_string, sub_string):
main_len = len(main_string)
sub_len = len(sub_string)
for i in range(main_len - sub_len + 1):
if main_string[i:i + sub_len] == sub_string:
return True
return False
# Get user input
main_string = input("Enter the main string: ")
sub_string = input("Enter the substring to check: ")
# Check if the substring is present
result = is_substring_present(main_string, sub_string)
# Print the result
if result:
print(f"The substring '{sub_string}' is present in the string '{main_string}'.")
else:
print(f"The substring '{sub_string}' is not present in the string '{main_string}'.")

Output:
Program-11:

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


1)addition 2)insertion 3)slicing
Program:
def perform_operations(lst):
"""Performs addition, insertion, and slicing operations on a list."""
while True:
print("\nList Operations:")
print("1. Add element")
print("2. Insert element")
print("3. Slice list")
print("4. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
element = int(input("Enter element to add: "))
[Link](element)
print("List after addition:", lst)
elif choice == 2:
index = int(input("Enter index for insertion: "))
element = int(input("Enter element to insert: "))
[Link](index, element)
print("List after insertion:", lst)
elif choice == 3:
start = int(input("Enter start index for slicing: "))
end = int(input("Enter end index for slicing: "))
sliced_list = lst[start:end]
print("Sliced list:", sliced_list)
elif choice == 4:
break
else:
print("Invalid choice!")
# Get initial list from user
lst = []
num_elements = int(input("Enter number of elements: "))
for i in range(num_elements):
element = int(input(f"Enter element {i+1}: "))
[Link](element)
print("Initial list:", lst)
perform_operations(lst)
Output:
Program-12:

Aim: Write a program to perform any 5 built-in functions by taking any list.
Program:
# Function to get a list of numbers from user input
def get_user_list():
user_input = input("Enter a list of numbers separated by spaces: ")
# Convert input string to a list of integers
number_list = list(map(int, user_input.split()))
return number_list
# Function to display the results of various built-in functions on the list
def display_list_functions(number_list):
print("List:", number_list)
print("Length of the list:", len(number_list))
print("Maximum value in the list:", max(number_list))
print("Minimum value in the list:", min(number_list))
print("Sum of the list elements:", sum(number_list))
print("Sorted list:", sorted(number_list))
# Main program execution
if name == " main ":
numbers = get_user_list()
display_list_functions(numbers)
Output:
UNIT-3
Program-13:

Aim: Write a program to create tuples (name, age, address, college) for at least two
members and concatenate the tuples and print the concatenated tuples.
Program:
def get_member_details():
# Get details for a member from user input
name = input("Enter name: ")
age = int(input("Enter age: "))
address = input("Enter address: ")
college = input("Enter college: ")
return (name, age, address, college)
# Get details for two members
print("Enter details for the first member:")
member1 = get_member_details()
print("Enter details for the second member:")
member2 = get_member_details()
# Concatenate the tuples
concatenated_tuples = member1 + member2
# Print the concatenated tuples
print("\nConcatenated Tuples:")
print(concatenated_tuples)

Output:
PS D:\python\2-1 lab> py [Link]
Enter details for the first member:
Enter name: John
Enter age: 21
Enter address: Nellore
Enter college: SVCN
Enter details for the second member:
Enter name: Jack
Enter age: 20
Enter address: Rajupalem
Enter college: SVEN

Concatenated Tuples:
('John', 21, 'Nellore', 'SVCN', 'Jack', 20, 'Rajupalem', 'SVEN')
PS D:\python\2-1 lab>
Program-14:

Aim: Write a program to count the number of vowels in a string (No control flow
allowed).
Program:
def count_vowels(s):
# Define vowels
vowels = "aeiouAEIOU"
# Use a list comprehension to filter out vowels and then get the length of the list
vowel_count = sum(char in vowels for char in s)
return vowel_count
# Example usage
input_string = input("Enter a string: ")
print("Number of vowels:", count_vowels(input_string))

Output:
Program-15:

Aim: Write a program to check if a given key exists in a dictionary or not.


Program:
def check_key_in_dict(d, key):
# Check if the key is in the dictionary
return key in d
# Example dictionary
example_dict = {
"name": "Jack",
"age": 20,
"address": "Nellore",
"college": "SVCN"
}
# Get key from user
key_to_check = input("Enter the key to check: ")
# Check if the key exists in the dictionary
if check_key_in_dict(example_dict, key_to_check):
print(f"The key '{key_to_check}' exists in the dictionary.")
else:
print(f"The key '{key_to_check}' does not exist in the dictionary.")

Output:
Program-16:

Aim: Write a program to add a new key-value pair to an existing dictionary.


Program:
def add_key_value(d, key, value):
# Add the new key-value pair to the dictionary
d[key] = value
return d
# Example dictionary
example_dict = {
"name": "Jack",
"age": 20,
"address": "Nellore",
"college": "SVCN"
}
# Get new key-value pair from user
new_key = input("Enter the new key: ")
new_value = input("Enter the new value: ")
# Add the new key-value pair to the dictionary
updated_dict = add_key_value(example_dict, new_key, new_value)
# Print the updated dictionary
print("\nUpdated Dictionary:")
print(updated_dict)

Output:
Program-17:

Aim: Write a program to sum all the items in a given dictionary.


Program:
def sum_dictionary_items(d):
# Sum all the values in the dictionary
return sum([Link]())
# Example dictionary
example_dict = {
"item1": 10,
"item2": 20,
"item3": 30,
"item4": 40
}
# Calculate the sum of all items
total_sum = sum_dictionary_items(example_dict)
# Print the result
print("The sum of all items in the dictionary is:", total_sum)

Output:
UNIT-4
Program-18:

Aim: 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.
Program:
def sort_and_lower_words(input_file, output_file):
try:
# Read words from the input file
with open(input_file, 'r') as file:
words = [Link]().split()
# Convert words to lower case and sort them
sorted_words = sorted([Link]() for word in words)
# Write sorted words to the output file
with open(output_file, 'w') as file:
for word in sorted_words:
[Link](word + '\n')
print(f"Sorted words have been written to {output_file}")
except FileNotFoundError:
print(f"The file {input_file} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Example usage
input_file = '[Link]' # Replace with your input file name
output_file = '[Link]' # Replace with your output file name
sort_and_lower_words(input_file, output_file)

Input File: // Create a file named [Link] in the same directory as your Python script and
add the following words:

Apple
banana
Cherry
date
Elderberry
FIG
Grape
ORANGE
Output File:
Program-19:

Aim: Write a Python program to print each line of a file in reverse order.
Program:
def reverse_lines_in_file(filename):
try:
with open(filename, 'r') as file:
lines = [Link]()
for line in lines:
print([Link]()[::-1])
except FileNotFoundError:
print(f"The file {filename} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Replace '[Link]' with the path to your file
reverse_lines_in_file('[Link]')

Input file: // Create a file named [Link] in the same directory as your Python script
and add the following lines:

Hello, world!
Python programming is fun.
Reverse these lines.

Output:
Program-20:

Aim: Python program to compute the number of characters, words and lines in a file.
Program:
def compute_file_statistics(filename):
try:
with open(filename, 'r') as file:
lines = [Link]()
num_lines = len(lines)
num_words = sum(len([Link]()) for line in lines)
num_chars = sum(len(line) for line in lines)
print(f"Number of lines: {num_lines}")
print(f"Number of words: {num_words}")
print(f"Number of characters: {num_chars}")
except FileNotFoundError:
print(f"The file {filename} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Replace '[Link]' with the path to your file
compute_file_statistics('[Link]')

Input file: // Create a file named [Link] in the same directory as your Python script
and add the following lines:

Hello, world!
Python programming is fun.
Count these lines, words, and characters.

Output:
Program-21:

Aim: Write a program to create, display, append, insert and reverse the order of the items
in the array.
Program:
def display_array(arr):
print("Current array:", arr)
def main():
array = []
while True:
print("\nOptions:")
print("1. Create an array")
print("2. Display the array")
print("3. Append an item")
print("4. Insert an item")
print("5. Reverse the array")
print("6. Exit")
choice = input("Enter your choice (1-6): ")
if choice == '1':
array = input("Enter elements separated by spaces: ").split()
print("Array created.")
elif choice == '2':
display_array(array)
elif choice == '3':
item = input("Enter item to append: ")
[Link](item)
print(f"Item '{item}' appended.")
elif choice == '4':
item = input("Enter item to insert: ")
index = int(input("Enter position to insert at (0-based index): "))
if 0 <= index <= len(array):
[Link](index, item)
print(f"Item '{item}' inserted at position {index}.")
else:
print("Invalid index.")
elif choice == '5':
[Link]()
print("Array reversed.")
elif choice == '6':
print("Exiting.")
break

else:
print("Invalid choice. Please try again.")
if name == " main ":
main()
Output:
Program-22:

Aim: Write a program to add, transpose and multiply two matrices.


Program:
def get_matrix_input(prompt):
"""Get matrix input from user."""
rows = int(input(f"Enter the number of rows for {prompt}: "))
cols = int(input(f"Enter the number of columns for {prompt}: "))
matrix = []
print(f"Enter the elements for {prompt} row by row (space-separated):")
for i in range(rows):
row = list(map(int, input(f"Row {i + 1}: ").split()))
if len(row) != cols:
print("Invalid number of columns. Please enter again.")
return get_matrix_input(prompt)
[Link](row)
return matrix
def print_matrix(matrix, name):
"""Print the matrix with its name."""
print(f"{name} matrix:")
for row in matrix:
print(row)
def add_matrices(A, B):
"""Add two matrices."""
if len(A) != len(B) or len(A[0]) != len(B[0]):
raise ValueError("Matrices must have the same dimensions for addition.")
return [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
def transpose_matrix(A):
"""Transpose a matrix."""
return [[A[j][i] for j in range(len(A))] for i in range(len(A[0]))]
def multiply_matrices(A, B):
"""Multiply two matrices."""
if len(A[0]) != len(B):
raise ValueError("Number of columns of A must be equal to number of rows of B.")
result = [[0] * len(B[0]) for _ in range(len(A))]
for i in range(len(A)):
for j in range(len(B[0])):
for k in range(len(B)):
result[i][j] += A[i][k] * B[k][j]
return result
def main():
# Get matrix A
matrix_A = get_matrix_input("Matrix A")
print_matrix(matrix_A, "Matrix A")
# Get matrix B
matrix_B = get_matrix_input("Matrix B")
print_matrix(matrix_B, "Matrix B")
# Add matrices
try:
sum_matrix = add_matrices(matrix_A, matrix_B)
print_matrix(sum_matrix, "Sum")
except ValueError as e:
print(e)
# Transpose matrices
transposed_A = transpose_matrix(matrix_A)
transposed_B = transpose_matrix(matrix_B)
print_matrix(transposed_A, "Transposed Matrix A")
print_matrix(transposed_B, "Transposed Matrix B")
# Multiply matrices
try:
product_matrix = multiply_matrices(matrix_A, matrix_B)
print_matrix(product_matrix, "Product")
except ValueError as e:
print(e)
if name == " main ":
main()

Output:
Program-23:

Aim: Write a Python program to create a class that represents a shape. Include methods to
calculate its area and perimeter. Implement subclasses for different shapes like circle,
triangle, and square.
Program:
import math
class Shape:
def area(self):
raise NotImplementedError
def perimeter(self):
raise NotImplementedError
class Circle(Shape):
def init (self):
[Link] = float(input("Enter the radius of the circle: "))
def area(self):
return [Link] * [Link]**2
def perimeter(self):
return 2 * [Link] * [Link]
class Triangle(Shape):
def init (self):
self.side1 = float(input("Enter the first side of the triangle: "))
self.side2 = float(input("Enter the second side of the triangle: "))
self.side3 = float(input("Enter the third side of the triangle: "))
def area(self):
s = (self.side1 + self.side2 + self.side3) / 2
return [Link](s * (s - self.side1) * (s - self.side2) * (s - self.side3))
def perimeter(self):
return self.side1 + self.side2 + self.side3
class Square(Shape):
def init (self):
[Link] = float(input("Enter the side of the square: "))
def area(self):
return [Link]**2
def perimeter(self):
return 4 * [Link]
def main():
shape_type = input("Enter the shape type (circle, triangle, square): ")
if shape_type == "circle":
shape = Circle()
elif shape_type == "triangle":
shape = Triangle()
elif shape_type == "square":
shape = Square()
else:
print("Invalid shape type")
return
print("Area:", [Link]())
print("Perimeter:", [Link]())
if name == " main ":
main()

Output:
UNIT-5
Program-24:

Aim: Python program to check whether a JSON string contains complex object or not.
Program:
import json
def is_complex_object(data):
"""Check if the given data contains a complex object (nested dictionaries or lists)."""
if isinstance(data, dict):
for key, value in [Link]():
if isinstance(value, (dict, list)):
return True
if is_complex_object(value):
return True
elif isinstance(data, list):
for item in data:
if isinstance(item, (dict, list)):
return True
if is_complex_object(item):
return True
return False
def check_json_complexity(json_string):
"""Check if the JSON string contains a complex object."""
try:
data = [Link](json_string)
except [Link]:
print("Invalid JSON string.")
return False
return is_complex_object(data)
def main():
# Take JSON string input from the user
json_string = input("Enter a JSON string to check: ")
# Check if the JSON string contains a complex object
if check_json_complexity(json_string):
print("The JSON string contains a complex object.")
else:
print("The JSON string does not contain a complex object.")
if name == " main ":
main()
Output:
Program-25:

Aim: Python Program to demonstrate NumPy arrays creation using array () function.
Program:
import numpy as np
def create_array_from_input():
# Prompt the user to enter values for the array
input_values = input("Enter values separated by spaces: "
# Split the input string into a list of strings
input_list = input_values.split()
# Convert the list of strings to a list of floats
input_list = [float(value) for value in input_list]
# Create a NumPy array from the list
numpy_array = [Link](input_list)
return numpy_array
# Call the function and display the result
array = create_array_from_input()
print("NumPy Array created:")
print(array)

Output:
Program-26:

Aim: Python program to demonstrate use of ndim, shape, size, dtype.


Program:
import numpy as np
# Function to create a 1D array from user input
def create_1d_array():
length = int(input("Enter the number of elements for the 1D array: "))
array_1d = list(map(int, input(f"Enter {length} elements separated by spaces:
").split()))
if len(array_1d) != length:
print(f"Warning: Expected {length} elements, but received {len(array_1d)}.
Adjusting input.")
array_1d = array_1d[:length]
return [Link](array_1d)
# Function to create a 2D array from user input
def create_2d_array():
rows = int(input("Enter the number of rows for the 2D array: "))
cols = int(input("Enter the number of columns for the 2D array: "))
array_2d = []
print("Enter the elements row-wise, separated by spaces:")
for i in range(rows):
row = list(map(int, input().split()))
if len(row) != cols:
print(f"Warning: Expected {cols} columns, but received {len(row)}. Adjusting
input.")
row = row[:cols]
array_2d.append(row)
return [Link](array_2d)
# Function to create a 3D array from user input
def create_3d_array():
depth = int(input("Enter the number of matrices (depth) for the 3D array: "))
rows = int(input("Enter the number of rows for each matrix: "))
cols = int(input("Enter the number of columns for each matrix: "))
array_3d = []
print("Enter the elements for each matrix row-wise, separated by spaces:")
for d in range(depth):
matrix = []
print(f"Matrix {d + 1}:")
for r in range(rows):
row = list(map(int, input().split()))
if len(row) != cols:
print(f"Warning: Expected {cols} columns, but received {len(row)}. Adjusting
input.")
row = row[:cols]
[Link](row)
array_3d.append(matrix)
return [Link](array_3d)
# Create and display 1D array
array_1d = create_1d_array()
print("\n1D Array:")
print(array_1d)
print("Number of dimensions (ndim):", array_1d.ndim)
print("Shape of array (shape):", array_1d.shape)
print("Size of array (size):", array_1d.size)
print("Data type of array elements (dtype):", array_1d.dtype)
print()
# Create and display 2D array
array_2d = create_2d_array()
print("2D Array:")
print(array_2d)
print("Number of dimensions (ndim):", array_2d.ndim)
print("Shape of array (shape):", array_2d.shape)
print("Size of array (size):", array_2d.size)
print("Data type of array elements (dtype):", array_2d.dtype)
print()
# Create and display 3D array
array_3d = create_3d_array()
print("3D Array:")
print(array_3d)
print("Number of dimensions (ndim):", array_3d.ndim)
print("Shape of array (shape):", array_3d.shape)
print("Size of array (size):", array_3d.size)
print("Data type of array elements (dtype):", array_3d.dtype)

Output:
Program-27:

Aim: Python program to demonstrate basic slicing, integer and Boolean indexing.

Program:
# Import the numpy library for array operations
import numpy as np
# Function to demonstrate slicing
def slicing_example(arr):
print("\nSlicing Example:")
start = int(input("Enter the start index: "))
stop = int(input("Enter the stop index: "))
print(f"Slice from index {start} to {stop}:")
print(arr[start:stop])
# Function to demonstrate integer indexing
def integer_indexing_example(arr):
print("\nInteger Indexing Example:")
index = int(input("Enter the index of the element to access: "))
print(f"Element at index {index}:")
print(arr[index])
indices = input("Enter multiple indices (space-separated): ")
indices = [int(x) for x in [Link]()]
print(f"Elements at indices {indices}:")
print(arr[indices])
# Function to demonstrate Boolean indexing
def boolean_indexing_example(arr):
print("\nBoolean Indexing Example:")
threshold = int(input("Enter the threshold value: "))
mask = arr > threshold
print(f"Elements greater than {threshold}:")
print(arr[mask])
# Main function
def main():
# Create a sample array
arr = [Link]([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("Sample Array:")
print(arr)
# Call the example functions
slicing_example(arr)
integer_indexing_example(arr)
boolean_indexing_example(arr)
if name == " main ":
main()
Output:
Program-28:

Aim: Python program to find min, max, sum, cumulative sum of array

Program:
import numpy as np
def main():
# Take user input for the array
user_input = input("Enter the elements of the array separated by spaces: ")
arr = [Link]([int(x) for x in user_input.split()])
# Find the minimum value in the array
min_value = [Link](arr)
print(f"\nMinimum value: {min_value}")
# Find the maximum value in the array
max_value = [Link](arr)
print(f"Maximum value: {max_value}")
# Calculate the sum of all elements in the array
sum_value = [Link](arr)
print(f"Sum of all elements: {sum_value}")
# Calculate the cumulative sum of the array
cumulative_sum = [Link](arr)
print(f"Cumulative sum of the array: {cumulative_sum}")
if name == " main ":
main()

Output:
Program-29:

Aim: 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

Program:
import pandas as pd
# Create a dictionary with five keys, each representing a list of ten values from user input
data_dict = {}
for i in range(5):
key = input(f"Enter key {i+1}: ")
values = []
for j in range(10):
value = input(f"Enter value {j+1} for key {key}: ")
[Link](value)
data_dict[key] = values
# Convert the dictionary to a pandas DataFrame
df = [Link](data_dict)
# Print the first few rows of the DataFrame using head()
print("First few rows of the DataFrame:")
print([Link]())
# Perform various data selection operations
print("\nSelecting specific columns:")
user_input_columns = input("Enter column names (separated by commas): ")
columns = [[Link]() for col in user_input_columns.split(',')]
print(df[columns])
print("\nSelecting specific rows:")
user_input_rows = input("Enter row indices (separated by commas): ")
rows = [int([Link]()) for row in user_input_rows.split(',')]
print([Link][rows])
print("\nSelecting specific rows and columns:")
user_input_rows = input("Enter row indices (separated by commas): ")
user_input_columns = input("Enter column names (separated by commas): ")
rows = [int([Link]()) for row in user_input_rows.split(',')]
columns = [[Link]() for col in user_input_columns.split(',')]
print([Link][rows, columns])
print("\nFiltering data based on conditions:")
user_input_condition = input("Enter a condition (e.g., A > 5): ")
print([Link](user_input_condition))

Output:
Program-30:

Aim: 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

Program:
import pandas as pd
import [Link] as plt
# the DataFrame ffrom the above program
data = {
'A': [1, 2, 3, 4, 5],
'B': ['a', 'b', 'c', 'd', 'e'],
'C': [10.1, 20.2, 30.3, 40.4, 50.5],
'D': [True, False, True, False, True],
'E': ['apple', 'banana', 'cherry', 'date', 'elderberry']
}
df = [Link](data)
# Get the column names
column_names = list([Link])
# Ask the user to select two columns
print("Select two columns:")
for i, column in enumerate(column_names):
print("{}. {}".format(i+1, column))
column1_index = int(input("Enter the number of the first column: ")) - 1
column2_index = int(input("Enter the number of the second column: ")) - 1
column1 = column_names[column1_index]
column2 = column_names[column2_index]
# Create a scatter plot
[Link](figsize=(10, 6))
[Link](df[column1], df[column2])
[Link](column1)
[Link](column2)
[Link]('Scatter Plot of {} vs {}'.format(column1, column2))
[Link]()
# Create a line plot
[Link](figsize=(10, 6))
[Link](df[column1], df[column2], marker='o')
[Link](column1)
[Link](column2)
[Link]('Line Plot of {} vs {}'.format(column1, column2))
[Link]()

Output:

You might also like