0% found this document useful (0 votes)
26 views43 pages

Python Skill Course Lab Manual

The document outlines a series of Python programming experiments aimed at developing various skills, including finding the largest number among three, displaying prime numbers, swapping numbers, demonstrating operators, handling exceptions, and working with complex numbers. Each experiment includes a clear aim, program code, and output examples. The content is structured for educational purposes, targeting students in a computer science course.

Uploaded by

premishotas06
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)
26 views43 pages

Python Skill Course Lab Manual

The document outlines a series of Python programming experiments aimed at developing various skills, including finding the largest number among three, displaying prime numbers, swapping numbers, demonstrating operators, handling exceptions, and working with complex numbers. Each experiment includes a clear aim, program code, and output examples. The content is structured for educational purposes, targeting students in a computer science course.

Uploaded by

premishotas06
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/ 43

DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 1

Experiment 1

1.Write a program to find the largest element among three Numbers.

Aim:To find the largest element among three Numbers

Program:

#static input
num1, num2, num3 = 10 , 30 , 20
if num1 >= num2 and num1 >= num3:
print(num1)
elif num2 >= num1 and num2 >= num3:
print(num2)
else:
print(num3)

#Dynamic input
num1=int(input("Enter First Number: "))
num2=int(input("Enter Second Number: "))
num3=int(input("Enter Third Number: "))
if num1 >= num2 and num1 >= num3:
print(num1)
elif num2 >= num1 and num2 >= num3:
print(num2)
else:
print(num3)

Output:

30
Enter First Number: 55
Enter Second Number: 11
Enter Third Number: 99
99

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 2

Experiment 2
2.Write a Program to display all prime numbers within an interval

Aim:To display all prime numbers within an interval

Program:

lower = int(input("Enter lower limit: "))


upper = int(input("Enter upper Number: "))
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:

Enter lower limit: 60


Enter upper Number: 99
Prime numbers between 60 and 99 are:
61
67
71
73
79
83
89
97

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 3

Experiment 3
3.Write a program to swap two numbers without using a temporary variable

Aim:To swap two numbers without using a temporary variable

Program:

# Initial values
a=5
b = 10
# Display original values
print("Before swapping:")
print("a =", a)
print("b =", b)
# Swapping using tuple unpacking
a, b = b, a
# Display swapped values
print("After swapping:")
print("a =", a)
print("b =", b)

Output:

Before swapping:
a=5
b = 10
After swapping:
a = 10
b=5

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 4

Experiment 4
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 viii) Identity Operators

Aim: Demonstrate the following operators i) Arithmetic Operators ii) Relational Operators iii)
Assignment Operators iv) Logical Operators v) Bit wise Operators vi) Ternary Operator vii)
Membership Operators viii) Identity Operators

Program:

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

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

# Assignment Operators
a = 10
a += 5
print("Add and assign (a += 5):", a)
a -= 3
print("Subtract and assign (a -= 3):", a)
a *= 2
print("Multiply and assign (a *= 2):", a)
a /= 4
print("Divide and assign (a /= 4):", a)
a %= 2
print("Modulus and assign (a %= 2):", a)
# Logical Operators
a, b = True, False
print("AND (a and b):", a and b)
print("OR (a or b):", a or b)

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 5
print("NOT (not a):", not a)

# Bitwise Operators
x, y = 10, 4
print("Bitwise AND (x & y):", x & y)
print("Bitwise OR (x | y):", x | y)
print("Bitwise XOR (x ^ y):", x ^ y)
print("Bitwise NOT (~x):", ~x)
print("Left Shift (x << 1):", x << 1)
print("Right Shift (x >> 1):", x >> 1)

# Ternary Operator
x, y = 10, 20
result = "x is greater" if x > y else "y is greater or equal"
print("Ternary Operator result:", result)

# Membership Operators
list = [1, 2, 3, 4, 5]
print("5 in list:", 5 in list)
print("10 not in list:", 10 not in list)

# Identity Operators
a, b = [1, 2, 3], [1, 2, 3]
print("a is b:", a is b)
print("a is not b:", a is not b)

Output:

Addition: 15
Subtraction: 5
Multiplication: 50
Division: 2.0
Floor Division: 2
Modulus: 0
Exponentiation: 100000
Equal to: False
Not equal to: True
Greater than: True
Less than: False
Greater than or equal to: True
Less than or equal to: False
Add and assign (a += 5): 15
Subtract and assign (a -= 3): 12
Multiply and assign (a *= 2): 24
Divide and assign (a /= 4): 6.0
Modulus and assign (a %= 2): 0.0
AND (a and b): False
OR (a or b): True
NOT (not a): False

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 6
Bitwise AND (x & y): 0
Bitwise OR (x | y): 14
Bitwise XOR (x ^ y): 14
Bitwise NOT (~x): -11
Left Shift (x << 1): 20
Right Shift (x >> 1): 5
Ternary Operator result: y is greater or equal
5 in list: True
10 not in list: True
a is b: False
a is not b: True

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 7

Experiment 5
5.Write a program to add and multiply complex numbers

Aim: To add and multiply complex numbers(Enter first complex number i.e. 3+4j not 3+4i)

Program:

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


second = complex(input('Enter first complex number: '))
# Addition of complex number
addition = first + second
# Displaying Sum
print('SUM = ', addition)
# Multiplication of complex number
product = first * second
# Displaying Product
print('PRODUCT = ', product)

Output:

Enter first complex number: 3+4j


Enter first complex number: 5+8j
SUM = (8+12j)
PRODUCT = (-17+44j)

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 8

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

Aim: To print multiplication table of a given number

Program:

num = int(input(" Enter a number : "))


# using the for loop to generate the multiplication tables
print("Table of: ",num,”is”)
for a in range(1,21):
print(num,'x',a,'=',num*a)

Output:

Enter a number : 5
Table of: 5 is
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
5 x 11 = 55
5 x 12 = 60
5 x 13 = 65
5 x 14 = 70
5 x 15 = 75
5 x 16 = 80
5 x 17 = 85
5 x 18 = 90
5 x 19 = 95
5 x 20 = 100

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 9

Experiment 7
7.Writehow to Handle specific exceptions – like division of a number by zero in python

Aim: To Handle specific exceptions – like division of a number by zero

Program:

try:
# Prompt the user to enter two numbers
numerator = float(input("Enter the numerator: "))
denominator = float(input("Enter the denominator: "))
# Perform division
result = numerator / denominator

except ZeroDivisionError:
# Handle the specific exception for division by zero
print("Error: Cannot divide by zero!")

except ValueError:
# Handle a different specific exception for invalid input
print("Error: Please enter valid numbers!")

else:
# This block runs if no exceptions are raised
print("Result:", result)

finally:
# This block always executes, regardless of an exception
print("Execution complete.")

Output:
Enter the numerator: 10
Enter the denominator: 0
Error: Cannot divide by zero!
Execution complete.

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 10

Experiment 8
8. Write a program to define a function with multiple return values

Aim: To define a function with multiple return values

Program:

def fun():
str = "Aditya college of Engineering & Technology"
x = 20
return str, x
str, x = fun()
print(str)
print(x)

Output:

Aditya college of Engineering & Technology


20

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 11

Experiment 9
9.Write a program to define a function using default arguments

Aim: To define a function using default arguments

Program:

def add_numbers( a = 7, b = 8):


sum = a + b
print('Sum:', sum)
add_numbers(2, 3)
add_numbers(a = 2)
add_numbers()

Output:

Sum: 5
Sum: 10
Sum: 15

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 12

Experiment 10
10.Write a program to find the length of the string without using any library functions

Aim: To find the length of the string without using any library functions

Program:

string = 'Hello'
count = 0
for i in string:
count+=1
print(count)

Output: 5

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 13

Experiment 11
10.Write a program to check if the substring is present in a given string or not

Aim:To check if the substring is present in a given string or not

Program:

def sub_string(substring, mainstring):


if substring in mainstring:
print(F"{substring} is present in {mainstring}")
else:
print(F"{substring} is not present in {mainstring}")
sub_string("New", "NewYork")

Output:

New is present in NewYork

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 14

Experiment 12
12.Write a program to perform the given operations on a list: i. Addition ii. Insertion
iii. Slicing

Aim: To perform the given operations on a list: i. Addition ii. Insertion iii. Slicing

Program:

list = [1,2,3,4,5]
print("list", list)

#Addition
list.append(6)
print(F" After appending of 6, list is {list}")

#insertion
list.insert(1, 10)
print(F" After insertion 10 in 1 index, list is {list}")

#slicing
print(F" Slicing of list is {list[3:6]}")

Output:

list [1, 2, 3, 4, 5]
After appending of 6, list is [1, 2, 3, 4, 5, 6]
After insertion 10 in 1 index, list is [1, 10, 2, 3, 4, 5, 6]
Slicing of list is [3, 4, 5]

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 15

Experiment 13
13.Write a program to perform any 5 built-in functions by taking any list

Aim:To perform any 5 built-in functions by taking any list

Program:

# Taking list input from the user


numbers = list(map(int, input("Enter numbers separated by spaces: ").split()))

# 1. Using `min()` to find the smallest element


smallest = min(numbers)
print("Smallest element:", smallest)

# 2. Using `max()` to find the largest element


largest = max(numbers)
print("Largest element:", largest)

# 3. Using `sum()` to find the sum of all elements


total = sum(numbers)
print("Sum of elements:", total)

# 4. Using `len()` to get the number of elements


count = len(numbers)
print("Number of elements:", count)

# 5. Using `sorted()` to sort the list in ascending order


sorted_list = sorted(numbers)
print("Sorted list:", sorted_list)

Output:

Enter numbers separated by spaces: 5 2 9 1 7


Smallest element: 1
Largest element: 9
Sum of elements: 24
Number of elements: 5
Sorted list: [1, 2, 5, 7, 9]

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 16

Experiment 14
14.Write a program to create tuples (name, age, address, college) for at least two members
and concatenate the tuples and print the concatenated tuples

Aim:To create tuples (name, age, address, college) for at least two members and concatenate the
tuples and print the concatenated tuples

Program:

S1=("Name= Aditya", "Age = 20", "Address = CSE", "College = Adithya")


S2=("Name= Afrid", "Age = 21", "Address = CSE", "College = Adithya")
print(S1)
print(S2)
S3=S1+S2
print(S3)

Output:

('Name= Aditya', 'Age = 20', 'Address = CSE', 'College = Adithya')


('Name= Afrid', 'Age = 21', 'Address = CSE', 'College = Adithya')
('Name= Aditya', 'Age = 20', 'Address = CSE', 'College = Adithya', 'Name= Afrid', 'Age = 21',
'Address = CSE', 'College = Adithya')

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 17

Experiment 15
15. Write a program to count the number of vowels in a string (No control flow allowed)

Aim: To count the number of vowels in a string (No control flow allowed)

Program:

string = "Python Coders To Rule The World!"


vowels = "aeiouAEIOU"
count = sum(string.count(vowel) for vowel in vowels)
print(count)

Output:

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 18

Experiment 16
16.Write a program to check if a given key exists in a dictionary or not

Aim: To check if a given key exists in a dictionary or not

Program:

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


key='b'
print(key in d)
key='g'
print(key in d)

Output:

True
False

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 19

Experiment 17
17.Write a program to add a new key-value pair to an existing dictionary

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

Program:

dict = {'key1':'Python', 'key2':'is a '}


dict['key3'] = 'versatile '
dict['key4'] = 'and powerful '
dict['key5'] = 'programming'
dict['key6'] = 'language
'
print(dict)

Output:

{'key1': 'Python', 'key2': 'is a ', 'key3': 'versatile', 'key4': ‘and powerful ', 'key5': 'programming', 'key6':
'language'}

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 20

Experiment 18
18.Write a program to sum all the items in a given dictionary

Aim: To sum all the items in a given dictionary

Program:

def returnSum(myDict):

list = []
for i in myDict:
list.append(myDict[i])
final = sum(list)

return final

# Driver Function
dict = {'a': 100, 'b': 200, 'c': 300}
print("Sum :", returnSum(dict))

Output:

Sum : 600

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 21

Experiment 19
19. Write a python program to sort words in a file and put them in another file. The output
file should have only lower-case words, so any upper-case words from source must be lowered.

Aim: To 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_words_in_file(input_file, output_file):


try:

# Open the input file and read the words


with open(input_file, 'r') as f:
words = f.read().split()

# Convert words to lowercase and sort them alphabetically


words = [word.lower() for word in words]
sorted_words = sorted(words)

# Write the sorted words to the output file


with open(output_file, 'w') as f:
for word in sorted_words:
f.write(word + '\n')

print(f"Words successfully sorted and 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}")

# Get input file and output file names from the user
input_file = input("Enter the input file name (with extension): ")
output_file = input("Enter the output file name (with extension): ")

sort_words_in_file(input_file, output_file)
ds_in_file(input_file, output_file)

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 22
Output:

Enter the input file name (with extension): c:\Notepad\input.txt


Enter the output file name (with extension): c:\Notepad\output.txt
Words successfully sorted and written to c:\Notepad\output.txt

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 23

Experiment 20
20. Python program to print each line of a file in reverse order.

Aim: To print each line of a file in reverse order.

Program:

def print_lines_in_reverse(input_file_path, output_file_path):


try:
# Open the input file for reading
with open(input_file_path, 'r') as input_file:
lines = input_file.readlines() # Read all lines in the file

# Open the output file for writing


with open(output_file_path, 'w') as output_file:

# Reverse each line and write to the output file


for line in lines:
reversed_line = line.strip()[::-1] # Reverse and strip whitespace
output_file.write(reversed_line + '\n') # Write reversed line to output

print(f"Reversed lines successfully written to {output_file_path}")


except FileNotFoundError:
print(f"The file {input_file_path} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")
# Get input and output file paths from the user
input_file_path = input("Enter the full path to the input file (with extension): ")
output_file_path = input("Enter the full path to the output file (with extension): ")

print_lines_in_reverse(input_file_path, output_file_path)

Output:

Enter the full path to the input file (with extension): C:\Notepad\input.txt
Enter the full path to the output file (with extension): C:\Notepad\output.txt
Reversed lines successfully written to C:\Notepad\output.txt

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 24

Experiment 21
21. Python program to compute the number of characters, words and lines in a file

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

Program:

def count_file_contents():
# Get the file path from the user
file_path = input("Enter the full path to the input file (with extension): ")

try:
with open(file_path, 'r') as file:
lines = file.readlines() # Read all lines from the file

num_lines = len(lines) # Count lines


num_words = 0 # Initialize word count
num_characters = 0 # Initialize character count

for line in lines:


num_characters += len(line) # Count characters in the line
num_words += len(line.split()) # Count words in the line

# Display results
print(f"Number of lines: {num_lines}")
print(f"Number of words: {num_words}")
print(f"Number of characters: {num_characters}")

except FileNotFoundError:
print(f"The file {file_path} does not exist.")
except Exception as e:
print(f"An error occurred: {e}")

# Call the function to execute the program


count_file_contents()

Output:
Enter the full path to the input file (with extension): C:\Notepad\input.txt
Number of lines: 1
Number of words: 11
Number of characters: 47

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 25

Experiment 22
22. Python program to create, display, append, insert and reverse the order of the items in the
array

Aim: To create, display, append, insert and reverse the order of the items in the array

Program:

def create_array():
"""Create an array with initial items."""
return [1, 2, 3, 4, 5] # Example initial items

def display_array(arr):
"""Display the items in the array."""
print("Current array:", arr)

def append_to_array(arr, item):


"""Append an item to the end of the array."""
arr.append(item)
print(f"Item {item} appended to the array.")

def insert_into_array(arr, index, item):


"""Insert an item at a specific index in the array."""
if 0 <= index <= len(arr):
arr.insert(index, item)
print(f"Item {item} inserted at index {index}.")
else:
print("Index out of bounds.")

def reverse_array(arr):
"""Reverse the order of the items in the array."""
arr.reverse()
print("Array reversed.")

def main():
# Create an array
array = create_array()

while True:
print("\nMenu:")
print("1. Display array\t 2. Append item")
print("3. Insert item\t 4. Reverse array\t 5. Exit")
choice = input("Enter your choice (1-5): ")
if choice == '1':
display_array(array)
elif choice == '2':
item = input("Enter item to append: ")

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 26
append_to_array(array, item)
elif choice == '3':
index = int(input("Enter index to insert at: "))
item = input("Enter item to insert: ")
insert_into_array(array, index, item)
elif choice == '4':
reverse_array(array)
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice. Please select again.")

if __name__ == "__main__":
main()

Output:

Menu:
1. Display array 2. Append item
3. Insert item 4. Reverse array 5. Exit
Enter your choice (1-5): 1
Current array: [1, 2, 3, 4, 5]

Menu:
1. Display array 2. Append item
3. Insert item 4. Reverse array 5. Exit
Enter your choice (1-5): 2
Enter item to append: 6, 9, 10
Item 6, 9, 10 appended to the array.

Menu:
1. Display array 2. Append item
3. Insert item 4. Reverse array 5. Exit
Enter your choice (1-5): 3
Enter index to insert at: 3
Enter item to insert: 20
Item 20 inserted at index 3.

Menu:
1. Display array 2. Append item
3. Insert item 4. Reverse array 5. Exit
Enter your choice (1-5): 4
Array reversed.

Menu:
1. Display array 2. Append item
3. Insert item 4. Reverse array 5. Exit

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 27
Enter your choice (1-5): 1
Current array: ['6, 9, 10', 5, 4, '20', 3, 2, 1]

Menu:
1. Display array 2. Append item
3. Insert item 4. Reverse array 5. Exit
Enter your choice (1-5): 5
Exiting the program.

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 28

Experiment 23
23. Python program to add, transpose and multiply two matrices.

Aim: To add, transpose and multiply two matrices.

Program:

definput_matrix(rows, cols):
"""Input a matrix from the user."""
matrix = []
for _ in range(rows):
row = list(map(int, input("Enter row (space-separated): ").split()))
matrix.append(row)
return matrix

defadd_matrices(matrix1, matrix2):
"""Add two matrices."""
return [[matrix1[i][j] + matrix2[i][j] for j in range(len(matrix1[0]))] for i in range(len(matrix1))]

deftranspose_matrix(matrix):
"""Transpose a matrix."""
return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]

defmultiply_matrices(matrix1, matrix2):
"""Multiply two matrices."""
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix2[0])):
sum = 0
for k in range(len(matrix2)):
sum += matrix1[i][k] * matrix2[k][j]
row.append(sum)
result.append(row)
return result

def main():
# Input first matrix
rows1 = int(input("Enter the number of rows for the first matrix: "))
cols1 = int(input("Enter the number of columns for the first matrix: "))
print("Enter the first matrix:")
matrix1 = input_matrix(rows1, cols1)

# Input second matrix


rows2 = int(input("Enter the number of rows for the second matrix: "))
cols2 = int(input("Enter the number of columns for the second matrix: "))
print("Enter the second matrix:")

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 29
matrix2 = input_matrix(rows2, cols2)

# Matrix Addition
if rows1 == rows2 and cols1 == cols2:
print("\nAddition of matrices:")
result_add = add_matrices(matrix1, matrix2)
for row in result_add:
print(row)
else:
print("Matrices cannot be added (dimensions do not match).")

# Matrix Transpose
print("\nTranspose of the first matrix:")
transposed1 = transpose_matrix(matrix1)
for row in transposed1:
print(row)

print("\nTranspose of the second matrix:")


transposed2 = transpose_matrix(matrix2)
for row in transposed2:
print(row)

# Matrix Multiplication
if cols1 == rows2:
print("\nMultiplication of matrices:")
result_multiply = multiply_matrices(matrix1, matrix2)
for row in result_multiply:
print(row)
else:
print("Matrices cannot be multiplied (inner dimensions do not match).")

if __name__ == "__main__":
main()

Output:
Enter the number of rows for the first matrix: 2
Enter the number of columns for the first matrix: 2
Enter row (space-separated): 1 2
Enter row (space-separated): 3 4
Enter the number of rows for the second matrix: 2
Enter the number of columns for the second matrix: 2
Enter row (space-separated): 5 6
Enter row (space-separated): 7 8

Addition of matrices:
[6, 8]
[10, 12]

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 30

Transpose of the first matrix:


[1, 3]
[2, 4]

Transpose of the second matrix:


[5, 7]
[6, 8]

Multiplication of matrices:
[19, 22]
[43, 50]

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 31

Experiment 24
24. 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.

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.

Program:

import math

class Shape:
def area(self):
raise NotImplementedError

def perimeter(self):
raise NotImplementedError

class Circle(Shape):
def __init__(self, radius):
self.radius = radius

def area(self):
return math.pi * self.radius ** 2

def perimeter(self):
return 2 * math.pi * self.radius

class Triangle(Shape):
def __init__(self, base, height, side1, side2):
self.base = base
self.height = height
self.side1 = side1
self.side2 = side2

def area(self):
return 0.5 * self.base * self.height

def perimeter(self):
return self.base + self.side1 + self.side2

class Square(Shape):
def __init__(self, side):
self.side = side

def area(self):
return self.side ** 2

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 32

def perimeter(self):
return 4 * self.side

def main():
shapes = []
# Get Circle input
radius = float(input("Enter the radius of the circle: "))
shapes.append(Circle(radius))
# Get Triangle input
base = float(input("Enter the base of the triangle: "))
height = float(input("Enter the height of the triangle: "))
side1 = float(input("Enter the length of side 1 of the triangle: "))
side2 = float(input("Enter the length of side 2 of the triangle: "))
shapes.append(Triangle(base, height, side1, side2))
# Get Square input
side = float(input("Enter the side length of the square: "))
shapes.append(Square(side))
# Display area and perimeter for each shape
for shape in shapes:
print(f"{shape.__class__.__name__}: Area = {shape.area():.2f}, Perimeter =
{shape.perimeter():.2f}")

if __name__ == "__main__":
main()

Output:
Enter the radius of the circle: 4
Enter the base of the triangle: 4
Enter the height of the triangle: 4
Enter the length of side 1 of the triangle: 4
Enter the length of side 2 of the triangle: 4
Enter the side length of the square: 4
Circle: Area = 50.27, Perimeter = 25.13
Triangle: Area = 8.00, Perimeter = 12.00
Square: Area = 16.00, Perimeter = 16.00

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 33

Experiment 25
25. Python program to check whether a JSON string contains complex object or not.

Aim: To check whether a JSON string contains complex object or not.


Program:

import json

defis_complex_object(obj):
"""Check if the object is a complex object (dict or list)."""
return isinstance(obj, (dict, list))

defcheck_json_complexity(json_string):
try:
# Parse the JSON string
parsed_json = json.loads(json_string)

# Check if the parsed JSON is a complex object


if is_complex_object(parsed_json):
return True
else:
return False
except json.JSONDecodeError:
print("Invalid JSON string.")
return False
# Example JSON strings
json_string_1 = '{"name": "Alice", "age": 30, "hobbies": ["reading", "hiking"]}' # complex object
json_string_2 = '"Hello, world!"' # simple string
json_string_3 = '12345' # simple number
# Check if they are complex objects
print(f"JSON String 1 is complex: {check_json_complexity(json_string_1)}")
print(f"JSON String 2 is complex: {check_json_complexity(json_string_2)}")
print(f"JSON String 3 is complex: {check_json_complexity(json_string_3)}")

Output:
JSON String 1 is complex: True
JSON String 2 is complex: False
JSON String 3 is complex: False

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 34

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

Aim: To demonstrate NumPy arrays creation using array () function.

Program:

import numpy as np

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

print(arr)

print(type(arr))

Output:
[1 2 3 4 5]
<class 'numpy.ndarray'>

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 35

Experiment 27
27. Python program to demonstrate use of ndim, shape, size, dtype.

Aim: To demonstrate use of ndim, shape, size, dtype

Program:

import numpy as np

# Create a 2D NumPy array


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

# Display the array


print("Array:")
print(array_2d)

# Demonstrate the use of ndim


print("\nNumber of dimensions (ndim):", array_2d.ndim)

# Demonstrate the use of shape


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

# Demonstrate the use of size


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

# Demonstrate the use of dtype


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

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

Number of dimensions (ndim): 2


Shape of the array (shape): (2, 3)
Total number of elements (size): 6
Data type of the elements (dtype): int32

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 36

Experiment 28
28. Python program to demonstrate basic slicing, integer and Boolean indexing

Aim: To demonstrate basic slicing, integer and Boolean indexing

Program:

import numpy as np
# Create a sample NumPy array
array = np.array([[10, 20, 30, 40],
[50, 60, 70, 80],
[90, 100, 110, 120]])

print("Original Array:")
print(array)
# Basic slicing
print("\nBasic Slicing (first two rows and first three columns):")
sliced_array = array[:2, :3]
print(sliced_array)
# Integer indexing
print("\nInteger Indexing (selecting specific elements):")
# Selecting elements at (0, 1), (1, 2), and (2, 3)
integer_indexed_array = array[[0, 1, 2], [1, 2, 3]]
print(integer_indexed_array)
# Boolean indexing
print("\nBoolean Indexing (selecting elements greater than 60):")
boolean_indexed_array = array[array > 60]
print(boolean_indexed_array)

Output:
Original Array:
[[ 10 20 30 40]
[ 50 60 70 80]
[ 90 100 110 120]]

Basic Slicing (first two rows and first three columns):


[[10 20 30]
[50 60 70]]
Integer Indexing (selecting specific elements):
[ 20 70 120]
Boolean Indexing (selecting elements greater than 60):
[ 70 80 90 100 110 120]

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 37

Experiment 29
29. Python program to find min, max, sum, cumulative sum of array

Aim: To find min, max, sum, cumulative sum of array

Program:

import numpy as np

# Create a sample NumPy array


array = np.array([5, 10, 15, 20, 25])

# Find the minimum value


min_value = np.min(array)
print("Minimum value in the array:", min_value)

# Find the maximum value


max_value = np.max(array)
print("Maximum value in the array:", max_value)

# Find the sum of all elements


total_sum = np.sum(array)
print("Sum of all elements in the array:", total_sum)

# Find the cumulative sum of the array


cumulative_sum = np.cumsum(array)
print("Cumulative sum of the array:", cumulative_sum)

Output:
Minimum value in the array: 5
Maximum value in the array: 25
Sum of all elements in the array: 75
Cumulative sum of the array: [ 5 15 30 50 75]

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 38

Experiment 30
30. 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

Aim: To demonstrate 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
# Step 1: Create a dictionary with at least five keys, each representing a list of ten values
data = {
'Product': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
'Price': [10.99, 12.50, 8.75, 5.00, 15.99, 7.50, 9.99, 20.00, 13.50, 11.25],
'Stock': [100, 200, 150, 300, 120, 80, 60, 40, 250, 10],
'Category': ['Electronics', 'Electronics', 'Home', 'Home', 'Fashion',
'Fashion', 'Toys', 'Toys', 'Books', 'Books'],
'Rating': [4.5, 4.0, 4.2, 3.8, 4.9, 4.0, 3.5, 4.3, 4.7, 4.1]
}
# Step 2: Convert the dictionary into a pandas DataFrame
df = pd.DataFrame(data)
# Step 3: Apply head() function to the pandas DataFrame
print("First five rows of the DataFrame:")
print(df.head())
# Step 4: Perform various data selection operations on the DataFrame
# 4a. Selecting a single column (Product)
print("\nSelecting the 'Product' column:")
product_column = df['Product']
print(product_column)
# 4b. Selecting multiple columns (Price and Stock)
print("\nSelecting 'Price' and 'Stock' columns:")
price_and_stock = df[['Price', 'Stock']]
print(price_and_stock)
# 4c. Selecting rows where Price is greater than 10
print("\nSelecting rows where Price > 10:")
high_price = df[df['Price'] > 10]
print(high_price)

# 4d. Selecting the first five rows using index position


print("\nSelecting the first five rows using iloc:")
first_five_rows = df.iloc[:5]
print(first_five_rows)

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 39
# 4e. Selecting a specific row by index (for example, index 2)
print("\nSelecting the row at index 2:")
specific_row = df.iloc[2]
print(specific_row)

Output:
First five rows of the DataFrame:
Product Price Stock Category Rating
0 A 10.99 100 Electronics 4.5
1 B 12.50 200 Electronics 4.0
2 C 8.75 150 Home 4.2
3 D 5.00 300 Home 3.8
4 E 15.99 120 Fashion 4.9

Selecting the 'Product' column:


0 A
1 B
2 C
3 D
4 E
5 F
6 G
7 H
8 I
9 J
Name: Product, dtype: object

Selecting 'Price' and 'Stock' columns:


Price Stock
0 10.99 100
1 12.50 200
2 8.75 150
3 5.00 300
4 15.99 120
5 7.50 80
6 9.99 60
7 20.00 40
8 13.50 250
9 11.25 10

Selecting rows where Price > 10:


Product Price Stock Category Rating
0 A 10.99 100 Electronics 4.5
1 B 12.50 200 Electronics 4.0
4 E 15.99 120 Fashion 4.9
7 H 20.00 40 Toys 4.3
8 I 13.50 250 Books 4.7
9 J 11.25 10 Books 4.1

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 40

Selecting the first five rows using iloc:


Product Price Stock Category Rating
0 A 10.99 100 Electronics 4.5
1 B 12.50 200 Electronics 4.0
2 C 8.75 150 Home 4.2
3 D 5.00 300 Home 3.8
4 E 15.99 120 Fashion 4.9

Selecting the row at index 2:


Product C
Price 8.75
Stock 150
Category Home
Rating 4.2
Name: 2, dtype: object

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 41

Experiment 31
31. Select any two columns from the above data frame, and observe the change in one
attribute with respect to other attribute with scatter and plot operations in matplotlib

Aim: 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 matplotlib.pyplot as plt

# Step 1: Create a dictionary with at least five keys, each representing a list of ten values
data = {
'Product': ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
'Price': [10.99, 12.50, 8.75, 5.00, 15.99, 7.50, 9.99, 20.00, 13.50, 11.25],
'Stock': [100, 200, 150, 300, 120, 80, 60, 40, 250, 10],
'Category': ['Electronics', 'Electronics', 'Home', 'Home', 'Fashion',
'Fashion', 'Toys', 'Toys', 'Books', 'Books'],
'Rating': [4.5, 4.0, 4.2, 3.8, 4.9, 4.0, 3.5, 4.3, 4.7, 4.1]
}

# Step 2: Convert the dictionary into a pandas DataFrame


df = pd.DataFrame(data)

# Step 3: Select two columns to explore their relationship


x_column = 'Price' # Independent variable
y_column = 'Rating' # Dependent variable

# Step 4: Create a scatter plot to observe the relationship


plt.figure(figsize=(10, 6))
plt.scatter(df[x_column], df[y_column], color='blue', alpha=0.5)
plt.title('Scatter Plot of Rating vs Price')
plt.xlabel('Price')
plt.ylabel('Rating')
plt.grid()
plt.axhline(y=df[y_column].mean(), color='r', linestyle='--', label='Average Rating')
plt.axvline(x=df[x_column].mean(), color='g', linestyle='--', label='Average Price')
plt.legend()
plt.show()

# Step 5: Display the DataFrame for reference


print("DataFrame:")
print(df)

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 42

Ouptut:

DataFrame:
Product Price Stock Category Rating
0 A 10.99 100 Electronics 4.5
1 B 12.50 200 Electronics 4.0
2 C 8.75 150 Home 4.2
3 D 5.00 300 Home 3.8
4 E 15.99 120 Fashion 4.9
5 F 7.50 80 Fashion 4.0
6 G 9.99 60 Toys 3.5
7 H 20.00 40 Toys 4.3
8 I 13.50 250 Books 4.7
9 J 11.25 10 Books 4.

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)


DEPARTMENT OF CSE PYTHON SKILL COURSE PAGE | 43

Additional Experiment
Experiment 32
32. Python program to check whether a XML string contains complex object or not.

Program:

importxml.etree.ElementTree as ET
defis_complex_object(element):
# A complex object can be defined as:
# - Element has child elements, or
# - Element has attributes

iflen(element) > 0 or len(element.attrib) > 0:


return True
return False
defcontains_complex_object(xml_string):
try:
# Parse the XML string into an ElementTree object
root = ET.fromstring(xml_string)
# Check if root or any child element is a complex object
ifis_complex_object(root):
return True
# Recursively check child elements for complex objects
for child in root:
ifis_complex_object(child):
return True
return False
exceptET.ParseError as e:
print(f"Invalid XML: {e}")
return False
# Test the function
xml_string = """
<person>
<name>John</name>
<address>
<street>Main St</street>
<city>New York</city>
</address>
</person>
"""
ifcontains_complex_object(xml_string):
print("The XML contains a complex object.")
else:
print("The XML does not contain a complex object.")

Output:
The XML contains a complex object.

ROLL NO.: ADITYA COLLEGE OF ENGINEERING & TECHNOLOGY (A)

You might also like