[go: up one dir, main page]

0% found this document useful (0 votes)
33 views81 pages

Python Programming

The document outlines various Python programming experiments, including finding the largest of three numbers, displaying prime numbers within an interval, swapping two numbers without a temporary variable, and performing operations on complex numbers. It also includes tasks such as printing multiplication tables, defining functions with multiple return values, and checking for substrings in strings. Each experiment details the aim, system specifications, algorithms, flowcharts, programs, and outputs.

Uploaded by

rianamallipudi
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)
33 views81 pages

Python Programming

The document outlines various Python programming experiments, including finding the largest of three numbers, displaying prime numbers within an interval, swapping two numbers without a temporary variable, and performing operations on complex numbers. It also includes tasks such as printing multiplication tables, defining functions with multiple return values, and checking for substrings in strings. Each experiment details the aim, system specifications, algorithms, flowcharts, programs, and outputs.

Uploaded by

rianamallipudi
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
You are on page 1/ 81

UNIT:1 EXPERIMENT-1

Aim : Write a python program to find largest element among three numbers

System Specifications:16GB RAM,intel i5-10500 CPU@3.10GHz

Software Utilization:Python 3.11.4

Algorithm:

Step 1:Start

Step 2:Take the input values from user from num1,num2,num3

Step 3:Compare the numbers using conditional statements

Step 4:Print the number which is greater than the other two numbers as the greatest number

Flowchart:
Program:

num1=float(input("Enter first number:"))

num2=float(input("Enter second number:"))

num3=float(input("Enter third number:"))

if(num1>=num2) and (num1>=num3):

Largest=num1

elif(num2>=num1) and (num2>=num3):

Largest=num2

else:

Largest=num3

print(f"The largest is",Largest)

Output:

Enter first number:15.38

Enter second number:12.45

Enter third number:19

The largest is 19.0

UNIT-1 EXPERIMENT-2

Aim:-To write a program to display all prime numbers within an interval.

System specification:-16GB RAM, intel i5-10500 CPU @ 3.10GHz

Software requirement:- python 3.11.4

Algorithm:-

Step-1: start.

Step-2: Take the input values from the user for lower interval and upper interval.

step-3: By using the arithmetic operator(%) to find the prime numbers with in the intervals.

step-4: print or display the prime numbers.

step-5: stop.

Flowchart:-
Start

Read n

Set i =1
i<=n

count==2
n%==0

Count=count+1
display n is prime Display not
prime

i=i+1
stop

Program:-

#Python program to display all the prime numbers within an interval

lower = 900

upper 1000

print("Prime numbers between", lower, "and", upper, "are:")

for num in range(lower, upper + 1):

#all prime numbers are greater than 1

if num > 1:

for i in range(2, num):

if (num% i)=0

break

else:

print(num)

Output:-

Prime number between 900 and 1000 are:

907

911

919

929

937

941
947

953

967

971

977

983

991

997

Result:-

Program to display all prime numbers within an interval is executed.

Unit-1: Experiment 3

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

System Specifications : 16GB RAM, intel i5-10500 CPU @ 3.10GHz

Software Utilization : Python 3.11.4

Algorithm :

Step-1 : Start.

Step-2 : Take 2 values for variables x and y.

Step-3 : Swap the numbers using x,y = y,x.

Step-4 : Print the swapped variables.

Step-5 : Stop.

Flow chart :

Start
Program :

x=5

y = 10

x, y = y, x

print("x =", x)

print("y =", y)

Output :

x = 10

y=5

UNIT-1: EXPERIMENT 5

AIM: Write a program to add and multiply complex numbers.

System Specifications: 16GB RAM, Intel i5-10500 CPU@3.10GHZ

Software: Python 3.11.4

ALGORITHM:

Step 1: start

Step 2: Take input (C1 ,C2) complex numbers

Step 3: Enter the real part of first complex number

Step 4: Enter the imaginary part of first complex number

Step 5: Enter the real part of second complex number

Step 6: Enter the imaginary part of second complex number

Step 7: Add both complex numbers

(a+bi)+(c+di)

Step 8: multiply both complex numbers

(a+bi) * (c+di)
(ac+adi+bci-bd)

(ac-bd+(ad+bc)i)

Step 9: End

FLOWCHART:

SS

Start

Input C1 ,C2

Add=C1+C2
Multiply=C1*C2

Print
Add
Multiply

End
PROGRAM:

first = complex(input('Enter first complex number: '))

second = complex(input('Enter first complex number: '))

sum = first + second

product = first * second

print('SUM = ', sum)

print('PRODUCT',product)

OUTPUT:

Enter first complex number: 3+6j

Enter first complex number:6+12j

SUM = (9+18j)

PRODUCT (-54+72j)

RESULT:

Python program to add and multiply complex numbers is executed

UNIT-1: Program 6

 AIM: Print multiplication table of a given number

 Hardware requirement: Hp.2.63GHZ,Ram 16GB

 Software requirement: Python 3.11.4

 Algorithm:

Step 1: Start

Step 2: Read the number for which the multiplication

Step 3: Read the range up to which the multiplication table is

Required

Step 4: Initialise a loop variable 1 to 11

Step 5: Repeat until i<=limit


Step 6: Result = num*i

Print num*i=Result

Increment i by 1

Step 7: End!

 Flow chart:
Start

Print (“Enter n” Read n)

I=1

If

i<=10

Print i*n

i=i+1

Stop

 Program:

#Program to print multiplication table of a given number

#Function to print multiplication table

def multiplication_table(n):

for i in range(1,11):

print(f”{n}x{i}={n*i}”)

#Taking input from user

n= int(input(“Enter a number to print it’s multiplication table:”))

#Output

Multiplication_table(n)

 Output:

enter a number16

16x1=16
16x2=32

16x3=48

16x4=64

16x5=80

16x6=96

16x7=112

16x8=128

16x9=144

16x10=160

 Result:

Program to print multiplication table of a given number is executed

Unit-2: Experiment 1

Aim : To define a function with multiple return values

System Specifications : 16GB RAM, intel i5-10500 CPU @ 3.10GHz

Software Utilization : Python 3.11.4

Algorithm :

Step -1 : Start

Step-2 : Define a function.

Step-3 : Call function to store return values in memory.

Step-4 : Print the return values.

Step-5 : Assign the values to variables (name_1, name_2).

Step-6 : Print individual values.

Step-7 : Stop.
Flow chart :
Start

def name()

return
“python”,”programming”

print(name())

name_1,name_2 = name()

print(name_1,name_2)

Stop
Program :

def name():

return "python","programming"

print(name())

name_1, name_2 = name()

print(name_1, name_2)

Output :

('python', 'programming')

python programming

UNIT-2:

PROGRAM-2

AIM: To write a program to define a function using default arguments.

System Specifications :16GB RAM, intel i5-10500 CPU @ 3.10GHz

Software Utilization: Python 3.11.4

Algorithm:

Step-1: Start.

Step-2: Define the function. Step-3: Print the statement.

Step-4: Call the required functions. Step-5: Stop.

FLOWCHART:
Start

Student(firstname,
lastname=’Antony’,
standard=’fifth’)

Print (firstname,lastname,studies
in,standard,’standard’)

Print (firstname,lastname,studies

in,standard,’standard’)

Student(‘mark’)

Student(‘mark’,’

Hari’,’sixth’)
Student(firstname,
Student(‘mark’,’
astname=’Antony
l ’,
’)
standard=’fift
meclem h’)

Stop
PROGRAM:

def student(firstname, lastname ='Antony', standard ='Fifth'): print(firstname, lastname, 'studies in',
standard, 'Standard') student('Mark')

student('Mark', 'Hari', 'Sixth') student('Mark', 'Meclem')

OUTPUT:

Mark Antony studies in Fifth Standard Mark Hari studies in Sixth Standard

Mark Meclem studies in Fifth Standard

RESULT:

Program to define a function using default arguments has been executed.

UNIT:2

EXPERIMENT 3

AIM: Write a program to find length of the string without using any library functions.

System Specifications: 16GB RAM, Intel i5-10500 CPU@3.10GHZ

Software: Python 3.11.4

ALGORITHM:

STEP 1: Start

STEP 2: Input: Get the string from the user

STEP 3: Initialize: Set a counter variable count to 0

STEP 4: Check: If the string is empty (s==””):

. Go to step 7

STEP 5: Remove: Remove the first character from the string: s=s[1:]

STEP 6: Increment: Increase the counter: count= count + 1

STEP 7: Output: Print the value of count as the length of the string

STEP 8: End
FLOWCHART:

Start

Initialize
Count=0

String is empty
NO

Yes

Increment Count

Print Count

Stop
PROGRAM:

def string_length(name):

length = 0

for char in name:

length += 1 return length

name = "pythonprogramming" length = string_length(name) print(length)

OUTPUT: 17

RESULT:

A program to find length of the string without using any library functions is executed.

UNIT-2: Experiment 4

 AIM: To write a python program that checks if a given substring is present in a main string.

 SYSTEM REQUIRED: 16GB RAM,INTEL i5-10500 CPU@3.10GHZ.

 SYSTEM CONFIGURATION: Python(3.11.4)

 ALGORITHM:

 Step 1:start

 Step 2:Read the main string from the user.

 Step 3:Read the substring from the user.

 Step 4:Use (in) operator to see if the substring is present in the main
string or NOT.

 Step 5:if the substring in main string is found is TRUE.

If the substring in main string is not found is FALSE.

 Step 6:if(TRUE) print(“substring found!”)


 Step 7:if(FALSE) print(“substring not found!”)

 Step 8:stop!

 Flow-chart:

START

Input(‘enter main
string”)

Input(“enter
substring”)
If substring
in main
string:

YES NO

Print(“substring found”) Print(“substring not found”)

stop
 PROGRAM:

#taking the input from the user as string

#taking the input from the user as a substring

string=(input("enter main string:"))

substring=(input("enter substring:"))

print(“does”,substring,”exist in”,string,”?”)

#output

if substring in string:

print(“string found:”,substring)

else:

print(“string not found:”,substring)

 OUTPUT:

enter main string:christopher columbus found america 1492

enter substring:america

does america exist in christopher columbus found america 1492 ?

string found: america

 RESULT:

Program to find if the substring is present in main string or not is executed

Unit-2

Experiment-5

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

i.addition ii.insertion iii.slicing

SYSTEM SPECIFICATION:16GB RAM INTEL i5-10500 CPU @ 3.10GHZ

SOFTWARE REQUIREMENT:Python(3.10)
ALGORITHM:

Step-1:start

Step-2:initialise thelist

Step-3:add an element to insert

Step-4:insertion an element to the list

Step-5:slice the element into the list

Step-6:stop

FLOWCHART:

start

Initialize the list

Display the list

Addition operation

Insertion operation

Slicing operation

PROGRAME:-

def main():

my_list = [4, 28, 39, 46,47, 52]

print("Original list:", my_list)

element_to_add = int(input("Enter an element to add to the list:

"))

my_list.append(element_to_add)

print("List after addition:", my_list)


index_to_insert = int(input("Enter the index to insert an element:

"))

element_to_insert = int(input("Enter the element to insert: "))

if 0 <= index_to_insert <= len(my_list):

my_list.insert(index_to_insert, element_to_insert)

print("List after insertion:", my_list)

else:

print("Invalid index for insertion!")

start_index = int(input("Enter the start index for slicing: "))

end_index = int(input("Enter the end index for slicing: "))

if 0 <= start_index <= len(my_list) and 0 <= end_index <=

len(my_list):

sliced_list = my_list[start_index:end_index]

print("Sliced list:", sliced_list)

else:

print("Invalid indices for slicing!")

if __name__ == "__main__":

main()

OUTPUT:Original list: [4, 28, 39, 46, 47, 52]

Enter an element to add to the list:

RESULT:

A program to find length of the string


UNIT – 2 Program - 6

AIM: To write a program to perform any 5 built-in functions by taking any list

SYSTEM REQUIRED: 16GB RAM, INTEL i5-10500 CPU@3.10GHZ

SYSTEM CONFIGURATION: Python (3.11.4)

ALGORITHM:

STEP 1: Start

STEP 2: Input the list contain integers, strings, or a mix of both.

Step 3: Add an element at the end of list.

STEP 4: Remove the first occurrence of a specified element from the list.

STEP 5: Sort the list in ascending order.

STEP 6: Count the occurrences of a specified element in the list.

STEP 7: Reverse the element of the list.

STEP 8: Stop.

FLOW CHART:
Start

My _list

My list appends(3)

Print(“After
appends(3)”;)

My list remove(s)

Print(“After
remove(s)”)

My list sort( )

Print(“After
 PROGRAM:

#Sample list

my_list = [5, 2, 9, 1, 5, 6]

# 1. Append () - Add an element to the end of the list

my_list.append (3)

print ("After append (3):", my _list)

# 2. Remove () - Remove the first occurrence of a value

my_list.remove (5)

print ("After remove (5):", my _list) # 3.

sort () - Sort the list in ascending order.

my _list.sort ()

Print ("After sort ():", my _list)

# 4. Reverse () - Reverse the order of the list.

my _list.reverse ()

Print ("After reverse ():", my_list)

# 5. Count () - Count the occurrences of a value in the list

count_of_1 = my_list.count (1)

print ("Count of 1:", count_of_1)

 OUTPUT:

After append (3): [5, 2, 9, 1, 5, 6, 3]

After remove (5): [2, 9, 1, 5, 6, 3]

After sort (): [1, 2, 3, 5, 6, 9]

After reverse (): [9, 6, 5, 3, 2, 1]

UNIT-3 PROGRAME-1

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.

SYSTEM CONFIGURATION:-

16GB RAM, intel i5-10500 CPU @ 3.10GHz


SOFTWARE REQUIRED:-

Python 3.11.4

ALGORITHM :-

STEP-1:-Initialize an Empty List

STEP-2:- Iterate Through Members

STEP-3:-Extract Values and Form Tuple

STEP-4:-Add Tuple to List

STEP-5:-Return and Print Results

FLOWCHART:-

start

process

decision

process

end

PROGRAM:-

def create_tuples(members):

member_tuples = []

for member in members:


member_tuple = (member['name'], member['age'], member['address'], member['college'])

member_tuples.append(member_tuple)

return member_tuples

members = [

{'name': 'Alice', 'age': 20, 'address': 'Hyderabad', 'college': 'IIT Hyderabad'},

{'name': 'Bob', 'age': 22, 'address': 'Bangalore', 'college': 'IIM Bangalore'}

concatenated_tuples = create_tuples(members)

print(concatenated_tuples)

OUTPUT:-

[(‘Alice’, 20, ‘Hyderabad’, ‘IIT Hyderabad’), (‘Bob’, 22, ‘Bangalore’, ‘IIM Bangalore’)

RESULT:-

Program to create tuples (name, age, address, college) for at least two members and concatenate

the tuples and print the concatenated tuples is executed

Aim: To write a program to count the number of vowels in a string without control flow.

Software Requirements: Python 3.12.3

Hardware Requirements: HP INTEL i5, 2.5GHz, 16 Gb RAM

Algorithm:

Step 1: Start

Step 2: Create a function count_vowels(input_string) to count vowels in the input string.

Step 2: Define a string vowels = "aeiouAEIOU" containing all vowels.

Step 3: Use map(input_string.count, vowels) to count occurrences of each vowel in the input string.

Step 4: Apply sum() to the result of map() to get the total number of vowels.
Step 5: Return the total vowel count from the function.

Step 6: Prompt the user to enter a string using input().

Step 7: Call count_vowels(input_string) and print the total number of vowels in the string.

Step 8: Stop

Program:

def count_vowels(input_string):

vowels = "aeiouAEIOU"

return sum(map(input_string.count, vowels))

input_string =input("enter a string:")

print("Number of vowels: {count_vowels(input_string)}")


Flowchart:

Start

Take input from


user into variable
input_string

Use sum(map(input_string.count,
vowels)) function to calculate the
total number of vowels in the
input string.

Print the total


number of
vowels.

Stop
UNIT-3 PROGRAM -4

Aim: To write a program to add a new key-value pair to an existing dictionary

Software requirement: Python

Hardware requirement: HP i5, 2.5GHz, 16 GB RAM

Algorithm:

Step 1: Initialize my_dict as {'hello': 1, 'world': 2}.

Step 2: Define newkey from user input.

Step 3: Define newval from user input.

Step 4: Add the key-value pair to my_dict using my_dict[newkey] = newval.

Step 5: Print the dictionary using print(my_dict)


Flowchart:

START

Define variables newkey


and newval

Declare an existing
dictionary my_dict

Add the key value pair using


My_dict(newkey)=newval.

Print my_dict to
display output

STOP
Program:

my_dict={'hello':1,'world':2}

newkey=input('Enter a key:')

newval= int(input('Enter value:')

my_dict[newkey]=newval

print(my_dict)

output:

{ 'hello': 1,'world': 2}

Unit-3: Experiment 5

Aim : To write a python program to sum all the items in a given dictionary.

System Specifications : 16GB RAM, intel i5-10500 CPU @ 3.10GHz

Software : Python 3.11.4

Algorithm :

Step-1 : Start

Step-2 : open the file

Step-3 : declare and instalize a dictionaryionary

Step-4 : find the sum of all values in a dictionary

Step-5 : print the total sum

Step-6 : display the results


Step-7 : Stop

Flowchart :

Start

open the file

my_dictionary = {'a': 1, 'b': 2, 'c': 3}

total_sum =
sum_dictionary_items(my_dictionary)

display the result

print("Sum of dictionary items:", total_sum)


Stop

Program :

my_dictionary = {'a': 1, 'b': 2, 'c': 3}

total_sum = sum_dictionary_items(my_dictionary) print("Sum of dictionary items:", total_sum)

Output :

Sum of dictionary items: 6

zUNIT-4: PROGRAM-1

AIM: 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 form source must be lowered

Software Requirment:16GB RAM, INTEL i5-10500CPU@3.10HZ

System Configuration: Python (3.11.4)

Algorithm:

Step 1: open the input file and read the words

Step 2: convert all words to lowercase

Step 3: sort the words alphabetically

Step 4: write the sorted lowercase words to the output

Step 5: stop the program


Floechart:

start

Open source
file

Read words
from source file

Convert word to
lowercase
Store lowercase word
in list

Repeat for all words

Sort words

Open output file


Close both files

end

Program:

def sort_words_in_file(input_file,output_file):

try:

#Read words from the input file with open(input_file,’r’)as file:

Words=file.read().split()

#Convert words to lowercase and remove duplicates

lower_case_words=set(word.lower()for words in words)

#sort the words

Sorted_words=sorted(lower_case_words)

#write the sorted words to the output file

With open(output_file,’w’) as file:

For word in sorted_words:

File.write(word+’\n’)

Print(f’sorted words have been written to{output_file}.’)

Except exception as e:

Print(f’An error occurred:{e}’)

Input_file=’source.txt’

Output_file=’sorted_words.txt’

Sort_words_in_file,(input_file,output_file)
Output:

Hello World

This is a sample File

hello world!

this is a sample file.

Result: Program to sort words in a file and put them into another file. The output file should have
only lower-case words,so any upper-case words from source must be lowered is executed.

Unit-4: Experiment 3

Aim : To python program to compute the number of characters, words and lines in a file

System Specifications : 16GB RAM, intel i5-10500 CPU @ 3.10GHz

Software : Python 3.11.4

Algorithm :

Step-1 : Start

Step-2 : open the file

Step-3 : read the file content

Step-4 : calculate number of line,words,characters

Step-5 : error handling

Step-6 : display the results


Step-7 : Stop

Flowchart :

Start

Open file

Read file content

Content=file.read()

Calculate number of line

Calculate number

of word

Calculate number

of characters

print(f'Number of lines: {num_lines}')

print(f'Number of words: {num_words}')

print(f'Numbercharacters:

Error handling
STSTOP

Program :

def compute_file_statistics(file_path):

with open(file_path, 'r') as file:

content = file.read() # Read the entire file content

# Calculate number of lines

lines = content.splitlines()

num_lines = len(lines)

# Calculate number of words

words = content.split()

num_words = len(words)

# Calculate number of characters

num_characters = len(content)

# Display the results

print(f'Number of lines: {num_lines}')

print(f'Number of words: {num_words}')

print(f'Number of characters: {num_characters}')

except Exception as e:

print(f 'An error occurred: {e}')

# Example usage

file_path = 'example.txt' # Replace with your file name

compute_file_statistics(file_path)

Output :

Hello nice to meet u

Words: 5

Characters: 16

Lines: 1v
Unit-4: Experiment 4

Aim : To create, display, append, insert and reverse the order of the items in an array by using
Python.

System Specifications : 16GB RAM, intel i5-10500 CPU @ 3.10GHz

Software Utilization : Python 3.11.4

Algorithm :

Step-1 : Start

Step-2 : Create an empty array and display.

Step-3 : Append some elements into the array.

Step-4 : Insert an element at a specific index.

Step-5 : Reverse the order of elements in the array.

Step-6 : Display the result for each operation.

Step-7 : Stop
FLOWCHART:-

Start A

my_array.insert(1, 15)

my_array = []

print("Array after appending:",


my_array)
print("Empty array:", my_array)

my_array.reverse()
my_array.append(10)
my_array.append(20)
my_array.append(30)

print("Reversed array:", my_array)

print("Array after appending:",


my_array)

Stop

A
Program :

def array_operation():

# Create an empty array

my_array = []

# Display the empty array

print("Empty array:", my_array)

# Append elements to the array

my_array.append(10)

my_array.append(20)

my_array.append(30)

# Display the array after appending

print("Array after appending:", my_array)

# Insert an element at a specific index

my_array.insert(1, 15)

# Display the array after inserting

print("Array after inserting:", my_array)

# Reverse the order of elements in the array

my_array.reverse()

# Display the reversed array

print("Reversed array:", my_array)

# Call the function to perform the operations

array_operation()

Output :

Empty array: []

Array after appending: [10, 20, 30]

Array after inserting: [10, 15, 20, 30]

Reversed array: [30, 20, 15, 10]


UNIT 4

EXPERIMENT-5

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

SYSTEM SPECIFICATION:16GB,intel i5-10500 CPU @3.10GHz

SOFTWARE UTILIZATION : python 3.10

ALGORITHM :

Step1 : take the variables A,BC

Step2 : Make sure the number of columns in A is equal to the number of rows in B

Step3 : For each element in the product matrix, multiply each element in a row of A by the

Corresponding element in a column of B, and add the products together

Step4 : Repeat for all rows and columns

Step5 : Put the calculated elements in the correct positions to form the product matrix

Step6 : Take the first row of the matrix and make it the first column of the new transposed.

matrix

Step7 : Take the second row and make it the second column of the new transposed matrix

Repeat for all rows

Step8 : The transpose of the sum of two matrices is equal to the sum of the transposes of the

individual matrices.
:

Read rows and columns of matrix

Read elements of matrix

i=0 i<r i++

j=0 j<r j++

at[i][j]=a[j][i]

Print resultant
transpose matrix

STOP
PROGRAM :

def add_matrices(matrix_a, matrix_b):

rows = len(matrix_a)

cols = len(matrix_a[0])

result = [[0 for _ in range(cols)] for _ in range(rows)]

for i in range(rows):

for j in range(cols):

result[i][j] = matrix_a[i][j] + matrix_b[i][j]

return result

def transpose_matrix(matrix):

rows = len(matrix)

cols = len(matrix[0])

transposed = [[0 for _ in range(rows)] for _ in range(cols)]

for i in range(rows):

for j in range(cols):
transposed[j][i] = matrix[i][j]

return transposed

def multiply_matrices(matrix_a, matrix_b):

cols_a = len(matrix_a[0])

rows_b = len(matrix_b)

cols_b = len(matrix_b[0])

if cols_a != rows_b:

raise ValueError("Cannot multiply: number of columns in A must be equal to number of

rows in B.")

result = [[0 for _ in range(cols_b)] for _ in range(rows_a)]

for i in range(rows_a):

for j in range(cols_b):

for k in range(cols_a): # or range(rows_b)

result[i][j] += matrix_a[i][k] * matrix_b[k][j]

return result

def display_matrix(matrix):
for row in matrix:

print(row)

def main():

# Define two matrices

matrix_a = [

[1, 2, 3],

[4, 5, 6]

matrix_b = [

[7, 8, 9],

[10, 11, 12]

print("Matrix A:")

display_matrix(matrix_a)

print("\nMatrix B:")
display_matrix(matrix_b)

# Add matrices

added_matrix = add_matrices(matrix_a, matrix_b)

print("\nAdded Matrix (A + B):")

display_matrix(added_matrix)

# Transpose matrix A

transposed_matrix_a = transpose_matrix(matrix_a)

print("\nTransposed Matrix A:")

display_matrix(transposed_matrix_a)

# Transpose matrix B

transposed_matrix_b = transpose_matrix(matrix_b)

print("\nTransposed Matrix B:")

display_matrix(transposed_matrix_b)

# Multiply matrices

matrix_c = [
[1, 2],

[3, 4],

[5, 6]

print("\nMatrix C (for multiplication):")

display_matrix(matrix_c)

multiplied_matrix = multiply_matrices(matrix_a, matrix_c)

print("\nMultiplied Matrix (A * C):")

display_matrix(multiplied_matrix)

if name == " main ":

main()

OUTPUT :

Matrix A:

[1, 2, 3]

[4, 5, 6]

Matrix B:
[7, 8, 9]

[10, 11, 12]

Added Matrix (A + B):

[8, 10, 12]

[14, 16, 18]

Transposed Matrix A:

[1, 4]

[2, 5]

[3, 6]

Transposed Matrix B:

[7, 10]

[8, 11]

[9, 12]

Matrix C (for multiplication):

[1, 2]
[3, 4]

[5, 6]

Multiplied Matrix (A * C):

[22, 28]

[49, 64]

RESULT: a program to add, transpose and multiply two matrices is executed.

UNIT-4: Experiment 6

Aim : 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 using Python.

System Requirments : 16GB RAM, intel i5-10500 CPU @3.10GHz

Software Utilization : Python (3.10.4)

Algorithm:

Step 1: start

Step 2: define a class shape with methods area()&perimeter()

Step 3:create subclasses circle,triangle,square inheriting from

Shape

Step 4: Implement the circle subclass with _init_,area(),and

Perimeter() methods

Step 5:implement the triangle subclass with _init_,area(),and

Perimeter() methods

Step 6:implement the square subclass with _init_,area(),and


Perimeter() methods

Step 7: stop

Flow-chart:

start

Calculate area() and perimeter() of


shapes

Circle: Area=π*r^2

Perimeter=2*π*r

Triangle: Area=1/2*b*h

Perimeter=(sum of all
sides)

Square: Area=s*s

Perimeter=4*s

Print(area & perimeter of circle,


triangle, square)

stop
PROGRAM:

class circle():

def _init_(self,r):

self.radius=r

def area(self):

return self.radius**2*3.14

def perimeter(self):

return 2*self.radius*3.14

new_circle=circle(5) print(new_circle.area())

print(new_circle.perimeter())

class triangle():

def _init_(self,a,b,c):

self.side1=a

self.side2=b

self.side3=c

def perimeter(self):

return self.side1+self.side2+self.side3

def area(self):

s=(self.side1+self.side2+self.side3)/2

return (s*(s-self.side1)(s-self.side2)(s-self.side3))**0.5 new_triangle=triangle(1,2,3)

print(new_triangle.perimeter())

print(new_triangle.area())
class square():

def _init_(self,a):

self.side=a

def perimeter(self):

return self.side*4

def area(self):

return self.side**2

new_square=square(1)

print(new_square.perimeter())

print(new_square.area())

OUTPUT:

78.5

31.400000000000002

0.0

UNIT-5 EXPERIMENT-1

AIM: To write a Python program to check whether a JSON string contains complex object or not.

HARDWARE REQUIRED:
16GB RAM, INTEL i5-10500 CPU @ 3.10GHZ

SOFTWARE CONFIGURATION:
Python (3.12.3)

ALGORITHM:

Step-1: Parse the input JSON string into a Python object.

Step-2: Check the object

If it is a dictionary, look for any values that are dictionaries or lists.

Step-3: If it is a list, look for any items that are dictionaries or lists.
Step-4: If a dictionary or list is found within the object, return "Contains complex object."

Step-5: Otherwise, return "Does not contain complex object."

Step-6: Stop.
Flowchart : Start

Import JSON

Parse JSON string

If yes

Define complexity check

Apply complexity check

Print false
Print true

Is json
complex

Stop

PROGRAM:

import json

def contains_complex_object(obj):

if isinstance(obj, dict):
for value in obj.values():

if isinstance(value, (dict, list)):

return True

elif isinstance(obj, list):

for item in obj:

if isinstance(item, (dict, list)):

return True

return False

def check_json_for_complex(json_str):

try:

obj = json.loads(json_str)

if contains_complex_object(obj):

return "Contains complex object"

else:

return "Does not contain complex object"

except json.JSONDecodeError:

return "Invalid JSON"

json_str1 = '{"name": "William", "address": {"city": "New York", "zip": "10001"}}'

json_str2 = '{"name": "William", "age": 30}'

print(check_json_for_complex(json_str1)) # Output: Contains complex object

print(check_json_for_complex(json_str2)) # Output: Does not contain complex object

OUTPUT:

Contains complex object

Does not contain complex object


Unit-5 (Program-2)

AIM :

Python Program to demonstrate NumPy arrays creation using array () function.

System Specilizations :

16GB RAM, INTEL i5-10500 CPU @ 3.10GHZ.

Software required :

Python (3.12.3)

Algorithm :

Step 1 : Start

Step 2 : Import the NumPy library as np.

Step 3 : Create a 1D array using np.array() and display it.

Step 4 : Create a 2D array using np.array() with a nested list and display it.

Step 5 : Create a 3D array using np.array() with a nested list of lists and display it.

Step 6 : Create an array with a specified data type using np.array() and dtype parameter, and display
it.

Step 7 : End
Flowchart :

Start

Create 1D Array

Create 2D Array

Create 3D Array

Create Array with Specified Data Type

Print Array with Specified Data Type

End
Program :

# Importing the NumPy library

import numpy as np

# Creating a 1D array

array_1d = np.array([1, 2, 3, 4, 5])

print("1D Array:")

print(array_1d)

# Creating a 2D array

array_2d = np.array([[1, 2, 3], [4, 5, 6]])

print("\n2D Array:")

print(array_2d)

# Creating a 3D array

array_3d = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])

print("\n3D Array:")

print(array_3d)

# Specifying the data type of elements in the array

array_dtype = np.array([1, 2, 3, 4], dtype=float)

print("\nArray with Specified Data Type (float):")

print(array_dtype)

Output :

1D Array:

[1 2 3 4 5]

2D Array:

[[1 2 3]

[4 5 6]]
3D Array:

[[[1 2]

[3 4]]

[[5 6]

[7 8]]]

Array with Specified Data Type (float):

[1. 2. 3. 4.]

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

System Specifications : 16GB RAM, intel i5-10500 CPU @ 3.10GHz

Software : Python 3.11.4

Algorithm :

Step-1 : Start

Step-2 : Initialize the 2D NumPy array arr.

Step-3 Retrieve the number of dimensions (ndim) of arr and print it.

Step-4 : Retrieve the shape (shape) of arr and print it.

Step-5 : Retrieve the total number of elements (size) of arr and print it.

Step-6 : Retrieve the data type (dtype) of the elements of arr and print it.

Step-7: Stop.

Flowchart :

start
Initialize 2D array

Retrieve ndim

Print ndim

Retrieve shape

Print shape

Retrieve size

Print size

Retrieve dtype

Print dtype

stop

Program:

import numpy as np

# Create a 2D array (matrix)

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Demonstrating the use of ndim

print("Number of dimensions (ndim):", arr.ndim)


# Demonstrating the use of shape

print("Shape of the array:", arr.shape)

# Demonstrating the use of size

print("Total number of elements (size):", arr.size)

# Demonstrating the use of dtype

print("Data type of elements (dtype):", arr.dtype)

Output :

Number of dimensions (ndim): 2

Shape of the array: (3, 3)

Total number of elements (size): 9

Data type of elements (dtype): int64

Result : Python program to demonstrate use of ndim, shape, size, dtype is executed.

UNIT-5 PROGRAME-4

AIM: python program to demonstrate basic slicing, integer and Boolean indexing.

SYSTEM HARDWARE AND SOFTWARE REQUIRED: 16GB RAM, intel i5-10500 CPU @ 3.10GHz

SYSTEM CONFIGURATION: Software : Python 3.11.4

ALGORITHM:

STEP 1: start

STEP 2: import numpy as np

STEP 3: create an array and slice the array with steps

STEP 4: access the elements using integer indexing and Boolen indexing

STEP 5: print the results for all operations


STEP 6: stop

PROGRAM:

import numpy as np

arr = np.array([[1, 2, 3, 4, 5],

[6, 7, 8, 9, 10],

[11, 12, 13, 14, 15]])

print("Original Array:")

print(arr)

sliced_array = arr[0:2, 1:4]

print("\nSliced Array (rows 0 to 1, columns 1 to 3):")

print(sliced_array)

sliced_array2 = arr[::2, ::2]

print(sliced_array2)

print("\nInteger Indexing:")

element = arr[1, 3]

print("Element at (1, 3):", element)

integer_indexing = arr[[0, 2], [1, 3]]

print("Selected elements using integer indexing:", integer_indexing)

print("\nBoolean Indexing:")
FLOW CHART : START

Import numpy as np

Create an array

Print original array

slice the array with required steps

Print sliced array

Access all elements

Integer indexing &

Boolean indexing

Print results for all operations

END
OUTPUT:

Original Array:

[[10 20 30]

[40 50 60]

[70 80 90]]

Basic Slicing (First 2x2 Sub-array):

[[10 20]

[40 50]]

Integer Indexing:

Element at [0, 1]: 20

Element at [2, 2]: 90

Boolean Indexing (Elements > 50):

[60 70 80 90]

Unit-5: Experiment 5

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

Hardware Required: 16GB RAM, intel i5-10500 CPU @ 3.10GHz

Software Required: Python 3.11.4

Algorithm :

Step-1 : Start

Step-2 : Import numpy package as np.

Step-3 : Initialize array as arr = [10,20,30,40]

Step-4 : min = np. Min(arr)


Step-5 : max = np. Max(arr)

Step-6 : total sum = np.sum(arr)

Step-7 :Cumulative sum = np.cum(arr)

Step-8 : Display minimum value in array.

Step-9 : Display maximum value in array.

Step-10 : Display sum of element in array.

Step- 11: Display cumulative sum of array.

Step-12: Stop.

Flowchart :
Start

Import numpy as np

Arr = np.array([10,20,30,40,50])

Min = np.min(arr)

Max = np.max(arr)

Sum = np.sum(arr)

print(min,max,sum,cum sum)

Stop

Program:

Import numpy as np

#create a Numpy array


Arr = np.array[10,20,30,40,50]

#Find the minimum value in the array

Min_value = np.min(arr)

Print(“Minimum value:”, min_value

#Find the maximum value in the array

Max_value = np.max(arr)

Print(“Maximum value:”, max_value)

#Find the sum of all elements in the array

total_sum = np.sum(arr)

print(“Sum of all elements:”, total_sum)

#Find the cumulative sum of the array

Cumulative_sum = np.cumsum(arr)

Print(“cumulative sum of the array:”, cumulative_sum)

Output :

Minimum value : 10

Maximum value : 50

Sum of all elements : 150

Cumulative sum of the array : [10 30 60 100 150]

Result : Python program to find min, max, sum, cumulative sum of array is executed.

UNIT-5 EXPERIMENT-6

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 panda’s data frame and explore the data
through the data frame as follows: a) Apply head () function to the panda’s data frame b) Perform
various data selection operations on Data Frame.

SOFTWARE REQUIRED: Python 3.11 with installed pandas library

HARDWARE REQUIRED: 16 GB RAM, intel i5 10th gen, 1 TB HDD


ALGORITHM:

STEP-1: Start

STEP-2: Create Dictionary with at least five keys. Each key will represent a value which is a list
containing at least ten values

STEP-3: Convert Dictionary to panda’s data frame by using pd. Data Frame () function

STEP-4: Apply the head () Function to display the first five rows

STEP-5: Perform data selection operations (select specific rows, columns in data frame by applying
various indexing techniques).

STEP-6: Stop

Flow chart:
import pandas as pd
# Create a dictionary with five keys and lists as values
data =

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],

'B': [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],

'C': [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],

'D': [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],

'E': [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]

df = pd.DataFrame(data)
# Explore the data using pandas functions
# a) Apply head() function to display the first few rows of the DataFrame
print("First few rows using head():")
print(df.head(), "\n") # By default, head() shows the first 5 rows
# b) Perform various data selection operations on DataFrame
# Select a specific column (e.g., column 'A')
print("Column 'A':")
print(df['A'], "\n")
# Select multiple columns (e.g., columns 'A' and 'C')
print("Columns 'A' and 'C':")
print(df

'A', 'C'

, "\n")
# Select specific rows (e.g., first 3 rows)
print("First 3 rows:")
print(df.iloc[:3], "\n")
# Select rows based on condition (e.g., values in column 'B' greater than 15)
print("Rows where values in 'B' are greater than 15:")
‘B’

15

, "\n")

# Select a specific row using loc (e.g., row at index 4) print("Row at


index 4 using loc:") print(df.loc[4], "\n") # Select a specific element
using iloc (e.g., element at row 2, column 'C') ':") print(df.iloc[2,
df.columns.get_loc('C')], "\n")
PROGRAM:

import pandas as pd

# Create a dictionary with five keys and lists as values

data = {

'A': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],

'B': [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],

'C': [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],

'D': [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],

'E': [41, 42, 43, 44, 45, 46, 47, 48, 49, 50]

# Convert the dictionary to a pandas DataFrame

df = pd.DataFrame(data)

# Explore the data using pandas functions

# a) Apply head() function to display the first few rows of the DataFrame

print("First few rows using head():")

print(df.head(), "\n") # By default, head() shows the first 5 rows

# b) Perform various data selection operations on DataFrame

# Select a specific column (e.g., column 'A')

print("Column 'A':")

print(df['A'], "\n")

# Select multiple columns (e.g., columns 'A' and 'C')

print("Columns 'A' and 'C':")

print(df[['A', 'C']], "\n")

# Select specific rows (e.g., first 3 rows)

print("First 3 rows:")

print(df.iloc[:3], "\n")
# Select rows based on condition (e.g., values in column ‘B’ greater than 15)

Print(“Rows where values in ‘B’ are greater than 15:”)

Print(df[df[‘B’] > 15], “\n”)

# Select a specific row using `loc` (e.g., row at index 4)

Print(“Row at index 4 using loc:”)

Print(df.loc[4], “\n”)

# Select a specific element using `iloc` (e.g., element at row 2, column ‘C’)

Print(“Element at row 2, column ‘C’:”)

Print(df.iloc[2, df.columns.get_loc(‘C’)], “\n”)

OUTPUT:

First few rows using head():

ABCDE

0 1 11 21 31 41

1 2 12 22 32 42

2 3 13 23 33 43

3 4 14 24 34 44

4 5 15 25 35 45

Column ‘A’:

01

12

23

34

45

56

67

78

89

9 10

Name: A, dtype: int64

Columns ‘A’ and ‘C’:


AC

0 1 21

1 2 22

2 3 23

3 4 24

4 5 25

5 6 26

6 7 27

7 8 28

8 9 29

9 10 30

First 3 rows:

ABCDE

0 1 11 21 31 41

1 2 12 22 32 42

2 3 13 23 33 43

Rows where values in ‘B’ are greater than 15:

ABCDE

5 6 16 26 36 46

6 7 17 27 37 47

7 8 18 28 38 48

8 9 19 29 39 49

9 10 20 30 40 50

Row at index 4 using loc:

A5

B 15

C 25

D 35

E 45

Name: 4, dtype: int64

Element at row 2, column ‘C’:


23

RESULT: 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 is executed.

UNIT-5

EXPERIMENT-7:

Aim: TO create a data visualization tool that enables users to select two columns from a dataset and
generate scatter plots, line plots, and line plots with annotations to observe the change in one
attribute with respect to the other.

System Specifications : 16GB RAM, intel i5-10500 CPU @ 3.10GHz

Software : Python 3.11.4 with installed pandas libraries.

Algoritham:

Step 1: Start.

Step 2: Import Necessary Libraries and load the Dataset Load the dataset into a pandas DataFrame.

Step 3: Select Two Attributes Create a Scatter Plot Use matplotlib to create a scatter plot with the
selected attributes.

Step 4: Label the Axes and Add a Title and create a Line Plot.

Step 5: Create a Line Plot with Annotations and add annotations to label each data point. Display the
Plots.

Step 6: End.
Flow chart:
import pandas as pd

import matplotlib.pyplot as plt

data =

[1, 2, 3, 4, 5],

'B': [2, 4, 6, 8, 10],

'C': [10, 20, 30, 40, 50],

df = pd.DataFrame(data)

column1 = 'A'

column2 = 'B'

plt.figure(figsize=(10,6))

plt.scatter(df[column1],
df[column2], label=f'

column2

vs

column1
', marker='o')

plt.xlabel(column1)

plt.ylabel(column2)

plt.title(f'Line plot of

Column2

vs

')
column1
plt.legend()

Program:

import pandas as pd

import matplotlib.pyplot as plt

# Create a sample data frame

data = {'A': [1, 2, 3, 4, 5],

'B': [2, 4, 6, 8, 10],

'C': [10, 20, 30, 40, 50],

'D': [100, 200, 300, 400, 500]}

df = pd.DataFrame(data)
# Select two columns

column1 = 'A'

column2 = 'B'

# Plot the data

plt.figure(figsize=(10,6))

plt.scatter(df[column1], df[column2], label=f'{column2} vs {column1}')

plt.xlabel(column1)

plt.ylabel(column2)

plt.title(f'Scatter plot of {column2} vs {column1}')

plt.legend()

plt.show()

# Plot the data as a line plot

plt.figure(figsize=(10,6))

plt.plot(df[column1], df[column2], label=f'{column2} vs {column1}', marker='o')

plt.xlabel(column1)

plt.ylabel(column2)

plt.title(f'Line plot of {column2} vs {column1}')

plt.legend()

plt.show()

Output:

You might also like