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

PP Lab Manual

The document outlines various programming experiments in Python, including finding the largest of three numbers, displaying prime numbers, swapping numbers, demonstrating operators, and performing operations on complex numbers. Each experiment includes code snippets, example usage, and expected outputs. The document serves as a comprehensive guide for basic Python programming concepts and functions.

Uploaded by

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

PP Lab Manual

The document outlines various programming experiments in Python, including finding the largest of three numbers, displaying prime numbers, swapping numbers, demonstrating operators, and performing operations on complex numbers. Each experiment includes code snippets, example usage, and expected outputs. The document serves as a comprehensive guide for basic Python programming concepts and functions.

Uploaded by

22hr1a3027
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/ 49

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

Aim:

Program:

deffind_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

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

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

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

largest = find_largest(num1, num2, num3)

print(f"The largest number is {largest}")

Output:

Enter the first number: 10

Enter the second number: 55

Enter the third number: 7

The largest number is 55.0


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

defis_prime(n):

if n <= 1:

return False

for i in range(2, n):

if n % i == 0:

return False

return True

deffind_primes(start, end):

fornum in range(start, end + 1):

ifis_prime(num):

print(num, end=" ")

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

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

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


find_primes(start, end)

Output:

Enter the start of the interval: 1

Enter the end of the interval: 10

Prime numbers between 1 and 10 are:

2 3 5 7
Experiment 3:Write a program to swap two numbers without using a temporary
variable.

Defis_prime(n):

if n <= 1:

return False

for i in range(2, n):

if n % i == 0:

return False

return True

deffind_primes(start, end):

fornum in range(start, end + 1):

ifis_prime(num):

print(num, end=" ")

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

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

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

find_primes(start, end)

Output:

Enter the first number (a): 3

Enter the second number (b): 5

Before swapping: a = 3.0, b = 5.0

After swapping: a = 5.0, b = 3.0


4.Experiment:Demonstrate the following Operators in Python with suitable examples.

defdemonstrate_operators():

# Arithmetic Operators

a = 10

b = 3

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"Floor Division: {a} // {b} = {a // b}")

print(f"Modulus: {a} % {b} = {a % b}")

print(f"Exponentiation: {a} ** {b} = {a ** b}\n")

# Relational Operators

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}\n")

# Assignment Operators

print(f"Assignment Operators:")

a = 10

print(f"a = {a}")
a += 5

print(f"a += 5: {a}")

a -= 3

print(f"a -= 3: {a}")

a *= 2

print(f"a *= 2: {a}")

a /= 4

print(f"a /= 4: {a}")

a //= 2

print(f"a //= 2: {a}")

a %= 3

print(f"a %= 3: {a}")

a **= 2

print(f"a **= 2: {a}\n")

# Logical Operators

x = True

y = False
print(f"Logical Operators:")

print(f"x and y: {x and y}")

print(f"x or y: {x or y}")

print(f"not x: {not x}\n")

# Bitwise Operators

a = 10 # 1010 in binary

b = 4 # 0100 in binary

print(f"Bitwise Operators:")

print(f"a& b: {a & b}")

print(f"a | b: {a | b}")
print(f"a ^ b: {a ^ b}")

print(f"~a: {~a}")

print(f"a<< 1: {a << 1}")

print(f"a>> 1: {a >> 1}\n")

# Ternary Operator

a = 10

b = 20

print(f"Ternary Operator:")

result = "a is greater" if a > b else "b is greater"

print(result + "\n")

# Membership Operators

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

print(f"Membership Operators:")

print(f"3 in my_list: {3 in my_list}")

print(f"6 not in my_list: {6 not in my_list}\n")

# Identity Operators

print(f"Identity Operators:")

a = 10

b = 10

c = a

print(f"a is b: {a is b}")

print(f"a is not c: {a is not c}")

list1 = [1, 2, 3]

list2 = [1, 2, 3]

list3 = list1

print(f"list1 is list2: {list1 is list2}")


print(f"list1 is list3: {list1 is list3}")

print(f"list1 == list2: {list1 == list2}")

# Run the demonstration

demonstrate_operators()

Output:

Arithmetic Operators:

Addition: 10 + 3 = 13

Subtraction: 10 - 3 = 7

Multiplication: 10 * 3 = 30

Division: 10 / 3 = 3.3333333333333335

Floor Division: 10 // 3 = 3

Modulus: 10 % 3 = 1

Exponentiation: 10 ** 3 = 1000

Relational Operators:

a == b: False
a != b: True

a > b: True

a < b: False

a >= b: True

a <= b: False

Assignment Operators:

a = 10

a += 5: 15

a -= 3: 12

a *= 2: 24
a /= 4: 6.0

a //= 2: 3.0

a %= 3: 0.0

a **= 2: 0.0

Logical Operators:

x and y: False

x or y: True

not x: False

Bitwise Operators:

a& b: 0

a | b: 14

a ^ b: 14

~a: -11

a<< 1: 20

a>> 1: 5

Ternary Operator:

b is greater

Membership Operators:

3 in my_list: True

6 not in my_list: True

Identity Operators:

a is b: True

a is not c: False

list1 is list2: False


list1 is list3: True

list1 == list2: True

Experiment 6:

# Define a function to add complex numbers

defadd_complex(c1, c2):

return c1 + c2

# Define a function to multiply complex numbers

defmultiply_complex(c1, c2):

return c1 * c2

# Example usage

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): "))

sum_result = add_complex(c1, c2)

product_result = multiply_complex(c1, c2)

print(f"The sum of {c1} and {c2} is: {sum_result}")

print(f"The product of {c1} and {c2} is: {product_result}")

Output:

Enter the first complex number (in the form a+bj): 5+6j

Enter the second complex number (in the form a+bj): 2+3j

The sum of (5+6j) and (2+3j) is: (7+9j)

The product of (5+6j) and (2+3j) is: (-8+27j)


Experint 6:

defprint_multiplication_table(n, upto=10):

print(f"Multiplication Table for {n}:")

for i in range(1, upto + 1):

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

# Example usage

number = int(input("Enter a number to print its multiplication


table: "))

upto = int(input("Enter the range up to which you want to


print the table: "))

print_multiplication_table(number, upto)

Output:

Enter a number to print its multiplication table: 3

Enter the range up to which you want to print the table: 10

Multiplication Table for 3:


3 x 1 = 3

3 x 2 = 6

3 x 3 = 9

3 x 4 = 12

3 x 5 = 15

3 x 6 = 18

3 x 7 = 21

3 x 8 = 24

3 x 9 = 27

3 x 10 = 30
Experiment 7:

defcalculate_operations(a, b):

# Perform addition, subtraction, multiplication, and


division

addition = a + b

subtraction = a - b

multiplication = a * b

if b != 0:

division = a / b

else:

division = None # Handle division by zero

# Return all the results

return addition, subtraction, multiplication, division

# Example usage

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


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

add, sub, mul, div = calculate_operations(num1, num2)

print(f"Addition of {num1} and {num2} is: {add}")

print(f"Subtraction of {num1} and {num2} is: {sub}")

print(f"Multiplication of {num1} and {num2} is: {mul}")

if div is not None:

print(f"Division of {num1} and {num2} is: {div}")

else:
print(f"Division of {num1} by {num2} is not possible (division
by zero)")

Output:

Enter the first number: 5

Enter the second number: 7

Addition of 5.0 and 7.0 is: 12.0

Subtraction of 5.0 and 7.0 is: -2.0

Multiplication of 5.0 and 7.0 is: 35.0

Division of 5.0 and 7.0 is: 0.714


Experiment 8:

def greet(name, greeting="Hello", punctuation="!"):

"""Function to greet a person with a custom greeting and


punctuation."""

return f"{greeting}, {name}{punctuation}"

# Using all default arguments

print(greet("Gandhi"))

# Overriding the greeting

print(greet("Nehru", greeting="Hi"))

# Overriding the greeting and punctuation

print(greet("Modi", greeting="Good morning", punctuation="."))

# Overriding the punctuation


print(greet("Sundhar", punctuation="!!"))

Output:

Hello, Gandhi!

Hi, Nehru!

Good morning, Modi.

Hello, Sundhar!!
Experiment 9:

deffind_string_length(input_string):

length = 0

for char in input_string:

length += 1

return length

# Example usage

string = input("Enter a string: ")

length = find_string_length(string)

print(f"The length of the string '{string}' is: {length}")

Output:

Hello, Gandhi!

Hi, Nehru!
Good morning, Modi.

Hello, Sundhar!!
Experiment 10:

defcheck_substring(main_string, substring):

if substring in main_string:

return True

else:

return False

# Example usage

main_string = input("Enter the main string: ")

substring = input("Enter the substring to check: ")

ifcheck_substring(main_string, substring):

print(f"'{substring}' is present in '{main_string}'.")

else:

print(f"'{substring}' is not present in '{main_string}'.")

Output:

Enter the main string: Hello there Goodmorning

Enter the substring to check: there

'there' is present in 'Hello there Goodmorning'.


Experiment 11:

defperform_operations():

# Initial list

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

print(f"Initial list: {my_list}")

# i. Addition (append an element)

element_to_add = 6

my_list.append(element_to_add)

print(f"After adding {element_to_add}: {my_list}")

# ii. Insertion (insert an element at a specific position)

element_to_insert = 10

position_to_insert = 2

my_list.insert(position_to_insert, element_to_insert)

print(f"After inserting {element_to_insert} at position


{position_to_insert}: {my_list}")

# iii. Slicing (getting a sublist)


start_index = 1

end_index = 4

sliced_list = my_list[start_index:end_index]

print(f"Sliced list from index {start_index} to {end_index}:


{sliced_list}")

# Call the function to perform operations

perform_operations()

Output:

Initial list: [1, 2, 3, 4, 5]

After adding 6: [1, 2, 3, 4, 5, 6]


After inserting 10 at position 2: [1, 2, 10, 3, 4, 5, 6]

Sliced list from index 1 to 4: [2, 10, 3]

Experiment 12:

defperform_builtin_functions(my_list):

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

length = len(my_list)

print(f"Length of the list: {length}")

# 2.max(): Get the maximum value in the list

maximum = max(my_list)

print(f"Maximum value in the list: {maximum}")

# 3.min(): Get the minimum value in the list

minimum = min(my_list)

print(f"Minimum value in the list: {minimum}")

# 4.sum(): Get the sum of all elements in the list

total_sum = sum(my_list)

print(f"Sum of all elements in the list: {total_sum}")

# 5.sorted(): Get a sorted version of the list


sorted_list = sorted(my_list)

print(f"Sorted list: {sorted_list}")

my_list = [5, 3, 8, 6, 2, 7, 4, 1]

print(f"Original list: {my_list}\n")

perform_builtin_functions(my_list)

Output:

Original list: [5, 3, 8, 6, 2, 7, 4, 1]

Length of the list: 8

Maximum value in the list: 8


Minimum value in the list: 1

Sum of all elements in the list: 36

Sorted list: [1, 2, 3, 4, 5, 6, 7, 8]

Experiment 13:

member1 = ("Alice", 20, "123 Maple Street", "XYZ University")

member2 = ("Bob", 22, "456 Oak Avenue", "ABC College")

print(f"Member 1: {member1}")

print(f"Member 2: {member2}")

# Concatenating the tuples

concatenated_tuple = member1 + member2

# Printing the concatenated tuple

print(f"Concatenated tuple: {concatenated_tuple}")

Output:

Member 1: ('Alice', 20, '123 Maple Street', 'XYZ University')


Member 2: ('Bob', 22, '456 Oak Avenue', 'ABC College')

Concatenated tuple: ('Alice', 20, '123 Maple Street', 'XYZ


University', 'Bob', 22, '456 Oak Avenue', 'ABC College')
Experiment 14:

defcount_vowels(s):

vowels = 'aeiouAEIOU'

return sum(map(s.lower().count, vowels))

# Example usage

input_string = input("Enter a string: ")

vowel_count = count_vowels(input_string)

print(f"The number of vowels in the string is: {vowel_count}")

Output:

Enter a string: Kuppam Engineering College

The number of vowels in the string is: 10


Experiment 15:

defcheck_key_exists(dictionary, key):

return key in dictionary

sample_dict = {

"name": "Alice",

"age": 25,

"address": "123 Maple Street",

"college": "XYZ University"

key_to_check = input("Enter the key to check: ")

ifcheck_key_exists(sample_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:

Enter the key to check: name

The key 'name' exists in the dictionary.


Experiment 16:

defadd_key_value_pair(dictionary, key, value):

dictionary[key] = value

return dictionary

# Example usage

sample_dict = {

"name": "Alice",

"age": 25,

"address": "123 Maple Street",

"college": "XYZ University"

print(f"Original dictionary: {sample_dict}")

# Getting the new key and value from the user

new_key = input("Enter the new key to add: ")

new_value = input("Enter the value for the new key: ")

# Adding the new key-value pair to the dictionary

updated_dict = add_key_value_pair(sample_dict, new_key,


new_value)

print(f"Updated dictionary: {updated_dict}")


Output:

Original dictionary: {'name': 'Alice', 'age': 25, 'address':


'123 Maple Street', 'college': 'XYZ University'}

Enter the new key to add: Branch

Enter the value for the new key: CSM

Updated dictionary: {'name': 'Alice', 'age': 25, 'address':


'123 Maple Street', 'college': 'XYZ University', 'Branch':
'CSM'}
Experiment 17:

defsum_dictionary_values(dictionary):

return sum(dictionary.values())

# Example usage

sample_dict = {

"item1": 10,

"item2": 25,

"item3": 30,

"item4": 45

print(f"Dictionary: {sample_dict}")

# Calculate the sum of all values

total_sum = sum_dictionary_values(sample_dict)

print(f"The sum of all the values in the dictionary is:


{total_sum}")

Output:

Dictionary: {'item1': 10, 'item2': 25, 'item3': 30, 'item4':


45}

The sum of all the values in the dictionary is: 110


Experiment 18:

defsort_and_lowercase_words(input_filename, output_filename):

try:

# Read words from the input file

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

words = file.read().split()

# Convert words to lowercase and sort them

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

words.sort()

# Write sorted words to the output file

with open(output_filename, 'w') as file:

for word in words:


file.write(word + '\n')

print(f"Words have been sorted and written to


{output_filename}.")

except Exception as e:

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

# Example usage

input_filename = 'source.txt'

output_filename = 'sorted_words.txt'
sort_and_lowercase_words(input_filename, output_filename)

Output:

Words have been sorted and written to sorted_words.txt.

Source.txt

Sorted_words.txt
Experiment 19:

defprint_lines_in_reverse(input_filename):

try:

# Read lines from the input file

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

lines = file.readlines()

# Reverse the content of each line and print

for line in lines:

reversed_line = line.strip()[::-1]

print(reversed_line)

except Exception as e:

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

# Example usage

input_filename = 'source.txt'

print_lines_in_reverse(input_filename)

Output:

dlroWolleH

eliFtseT a sisihT

sdroWesaCreppUemoShtiW
Experiment 20:

defcount_file_contents(input_filename):

try:

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

lines = file.readlines()

num_lines = len(lines)

num_words = sum(len(line.split()) 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 Exception as e:

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

# Example usage

input_filename = 'source.txt'

count_file_contents(input_filename)

Output:

Number of lines: 3

Number of words: 11

Number of characters: 58
Experiment 21:

import array

defdisplay_array(arr):

print("Array:", arr.tolist())

def main():

# Create an array of integers

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

print("Initial array:")

display_array(arr)

# Append an item to the array

arr.append(6)
print("\nArray after appending 6:")

display_array(arr)

# Insert an item at a specific index

arr.insert(2, 9) # Insert 9 at index 2

print("\nArray after inserting 9 at index 2:")

display_array(arr)

# Reverse the order of the items in the array

arr.reverse()

print("\nArray after reversing the order of items:")


display_array(arr)

if __name__ == "__main__":

main()

Output:

Initial array:

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

Array after appending 6:

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

Array after inserting 9 at index 2:

Array: [1, 2, 9, 3, 4, 5, 6]

Array after reversing the order of items:

Array: [6, 5, 4, 3, 9, 2, 1]
Experiment 22:

importnumpy as np

defadd_matrices(matrix1, matrix2):

result = [[matrix1[i][j] + matrix2[i][j] for j in


range(len(matrix1[0]))] for i in range(len(matrix1))]

return result

deftranspose_matrix(matrix):

result = [[matrix[j][i] for j in range(len(matrix))] for i in


range(len(matrix[0]))]

return result

defmultiply_matrices(matrix1, matrix2):

result = [[sum(matrix1[i][k] * matrix2[k][j] for k in


range(len(matrix2))) for j in range(len(matrix2[0]))] for i in
range(len(matrix1))]

return result

defprint_matrix(matrix):

for row in matrix:

print(row)

# Example matrices

matrix1 = [

[1, 2, 3],

[4, 5, 6],
[7, 8, 9]

matrix2 = [

[9, 8, 7],

[6, 5, 4],

[3, 2, 1]

print("Matrix 1:")

print_matrix(matrix1)

print("\nMatrix 2:")

print_matrix(matrix2)

# Adding matrices

print("\nSum of Matrix 1 and Matrix 2:")

sum_matrix = add_matrices(matrix1, matrix2)


print_matrix(sum_matrix)

# Transposing matrix1

print("\nTranspose of Matrix 1:")

transpose_matrix1 = transpose_matrix(matrix1)

print_matrix(transpose_matrix1)

# Multiplying matrices

print("\nProduct of Matrix 1 and Matrix 2:")

product_matrix = multiply_matrices(matrix1, matrix2)

print_matrix(product_matrix)
Output:

Matrix 1:

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]

Matrix 2:

[9, 8, 7]

[6, 5, 4]

[3, 2, 1]

Sum of Matrix 1 and Matrix 2:

[10, 10, 10]

[10, 10, 10]

[10, 10, 10]

Transpose of Matrix 1:
[1, 4, 7]

[2, 5, 8]

[3, 6, 9]

Product of Matrix 1 and Matrix 2:

[30, 24, 18]

[84, 69, 54]

[138, 114, 90]


Experiment 23:

import math

# Base class for shapes

class Shape:

def area(self):

pass

def perimeter(self):

pass

# Subclass for Circle

class Circle(Shape):

def __init__(self, radius):


self.radius = radius

def area(self):

returnmath.pi * self.radius ** 2

def perimeter(self):

return 2 * math.pi * self.radius

# Subclass for Triangle

class Triangle(Shape):

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


self.a = a

self.b = b

self.c = c

def area(self):

s = (self.a + self.b + self.c) / 2

returnmath.sqrt(s * (s - self.a) * (s - self.b) * (s -


self.c))

def perimeter(self):

returnself.a + self.b + self.c

# Subclass for Square

class Square(Shape):

def __init__(self, side):

self.side = side

def area(self):

returnself.side ** 2

def perimeter(self):

return 4 * self.side

# Example usage

shapes = [

Circle(5),

Triangle(3, 4, 5),

Square(4)

]
for shape in shapes:

print(f"{shape.__class__.__name__}:")

print(f" Area: {shape.area():.2f}")

print(f" Perimeter: {shape.perimeter():.2f}")

print()

Output:

Circle:

Area: 78.54

Perimeter: 31.42

Triangle:

Area: 6.00

Perimeter: 12.00

Square:

Area: 16.00
Perimeter: 16.00
Experiment 24:

importjson

defcheck_json_complexity(json_str):

try:

parsed_json = json.loads(json_str)

# Check if the parsed JSON contains any nested


dictionaries or lists

return any(isinstance(value, (dict, list)) for value in


parsed_json.values())

exceptjson.JSONDecodeError:

print("Invalid JSON string.")

return False

# Example usage
json_str1 = '{"name": "Alice", "age": 30, "address": {"city":
"Wonderland", "zip": "12345"}}'

json_str2 = '{"name": "Bob", "age": 25, "hobbies": ["reading",


"swimming"]}'

json_str3 = '{"name": "Charlie", "age": 20}'

print("JSON String 1 contains complex object:",


check_json_complexity(json_str1))

print("JSON String 2 contains complex object:",


check_json_complexity(json_str2))

print("JSON String 3 contains complex object:",


check_json_complexity(json_str3))
Output:

JSON String 1 contains complex object: True

JSON String 2 contains complex object: True

JSON String 3 contains complex object: False

Experiment 25:

importnumpy as np

# Create a 1D array

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

print("1D Array:")

print(arr1)

print()

# Create a 2D array (matrix)

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

print("2D Array (Matrix):")

print(arr2)

print()

# Create a 3D array

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


print("3D Array:")

print(arr3)

Output:

1D Array:

[1 2 3 4 5]

2D Array (Matrix):

[[1 2 3]

[4 5 6]

[7 8 9]]

3D Array:
[[[1 2]

[3 4]]

[[5 6]

[7 8]]]

Experiment 26:

importnumpy as np

# Create a 1D array

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

print("1D Array:")

print("Array:", arr1)

print("Dimensions:", arr1.ndim)

print("Shape:", arr1.shape)

print("Size:", arr1.size)

print("Data Type:", arr1.dtype)

print()

# Create a 2D array (matrix)

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

print("2D Array (Matrix):")


print("Array:")

print(arr2)

print("Dimensions:", arr2.ndim)

print("Shape:", arr2.shape)

print("Size:", arr2.size)

print("Data Type:", arr2.dtype)

print()

# Create a 3D array

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

print("3D Array:")

print("Array:")
print(arr3)

print("Dimensions:", arr3.ndim)

print("Shape:", arr3.shape)

print("Size:", arr3.size)

print("Data Type:", arr3.dtype)

Output:

1D Array:

Array: [1 2 3 4 5]

Dimensions: 1

Shape: (5,)

Size: 5

Data Type: int32

2D Array (Matrix):

Array:

[[1 2 3]

[4 5 6]

[7 8 9]]
Dimensions: 2

Shape: (3, 3)

Size: 9

Data Type: int32

3D Array:

Array:

[[[1 2]

[3 4]]

[[5 6]

[7 8]]]

Dimensions: 3
Shape: (2, 2, 2)

Size: 8

Data Type: int32

Experiment 27:

importnumpy as np

# Creating a NumPy array

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

# Basic slicing

print("Original Array:", arr)

print("Slicing Examples:")

print("arr[2:5] =", arr[2:5]) # Slice from index 2 to 4


(except 5)

print("arr[:3] =", arr[:3]) # Slice from start to index 2

print("arr[3:] =", arr[3:]) # Slice from index 3 to end

print()

# Integer indexing

print("Integer Indexing Examples:")

print("arr[0] =", arr[0]) # Access element at index 0

print("arr[-1] =", arr[-1]) # using negative indexing

print("arr[[1, 3, 4]] =", arr[[1, 3, 4]]) # Access elements


at specified indices

print()

# Boolean indexing

print("Boolean Indexing Examples:")


mask = np.array([True, False, True, False, True]) # Boolean
mask

print("mask =", mask)

print("arr[mask] =", arr[mask])

Output:

Original Array: [1 2 3 4 5]

Slicing Examples:

arr[2:5] = [3 4 5]

arr[:3] = [1 2 3]

arr[3:] = [4 5]

Integer Indexing Examples:

arr[0] = 1

arr[-1] = 5

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

Boolean Indexing Examples:


mask = [ True False True False True]

arr[mask] = [1 3 5]
Experiment 28:

importnumpy as np

# Create a NumPy array

arr = np.array([3, 7, 1, 9, 5])

# Minimum value in the array

min_value = np.min(arr)

print("Minimum value:", min_value)

# Maximum value in the array

max_value = np.max(arr)
print("Maximum value:", max_value)

# Sum of all elements in the array

sum_value = np.sum(arr)

print("Sum of elements:", sum_value)

# Cumulative sum of elements in the array

cumsum_values = np.cumsum(arr)

print("Cumulative sum of elements:", cumsum_values)

Output:
Minimum value: 1

Maximum value: 9

Sum of elements: 25

Cumulative sum of elements: [ 3 10 11 20 25]

Experiment 29:

import pandas as pd

importnumpy as np

# Create a dictionary with at least five keys

data_dict = {

'A': np.random.randint(1, 100, 10),

'B': np.random.rand(10),

'C': ['apple', 'banana', 'cherry', 'date', 'elderberry',


'fig', 'grape', 'honeydew', 'imbe', 'jackfruit'],

'D': np.random.choice([True, False], 10),

'E': pd.date_range('2023-01-01', periods=10)

# Convert dictionary to Pandas DataFrame

df = pd.DataFrame(data_dict)

# Explore the DataFrame

print("DataFrame:")

print(df)

print()

# a) Apply head() function to the pandas data frame


print("Head of DataFrame:")

print(df.head())

print()

# b) Perform various data selection operations on Data Frame

print("Selection Operations:")

# Select specific columns

print("Selecting columns A and C:")

print(df[['A', 'C']])

print()

# Select rows based on conditions

print("Selecting rows where column D is True:")

print(df[df['D']])

print()

# Select rows and specific columns based on conditions

print("Selecting rows where column B > 0.5 and selecting


columns B and E:")
print(df.loc[df['B'] > 0.5, ['B', 'E']])

print()

Output:

DataFrame:

A B C D E

0 30 0.926616 apple True 2023-01-01

1 20 0.734918 banana False 2023-01-02

2 82 0.457964 cherry True 2023-01-03

3 97 0.834334 date False 2023-01-04


4 59 0.029665 elderberry True 2023-01-05

5 83 0.278007 fig False 2023-01-06

6 38 0.158589 grape True 2023-01-07

7 31 0.939041 honeydew False 2023-01-08

8 79 0.059962 imbe True 2023-01-09

9 10 0.670870 jackfruit False 2023-01-10

Head of DataFrame:

A B C D E

0 30 0.926616 apple True 2023-01-01

1 20 0.734918 banana False 2023-01-02

2 82 0.457964 cherry True 2023-01-03

3 97 0.834334 date False 2023-01-04

4 59 0.029665 elderberry True 2023-01-05

Selection Operations:

Selecting columns A and C:

A C
0 30 apple

1 20 banana

2 82 cherry

3 97 date

4 59 elderberry

5 83 fig

6 38 grape

7 31 honeydew

8 79imbe

9 10 jackfruit
Selecting rows where column D is True:

A B C D E

0 30 0.926616 apple True 2023-01-01

2 82 0.457964 cherry True 2023-01-03

4 59 0.029665 elderberry True 2023-01-05

6 38 0.158589 grape True 2023-01-07

8 79 0.059962 imbe True 2023-01-09

Selecting rows where column B > 0.5 and selecting columns B


and E:

B E

0 0.926616 2023-01-01

1 0.734918 2023-01-02

3 0.834334 2023-01-04
Experiment 30:

import pandas as pd

importnumpy as np

importmatplotlib.pyplot as plt

# Create a sample DataFrame (you can replace this with your


actual DataFrame)

data_dict = {

'A': np.random.randint(1, 100, 10),

'B': np.random.rand(10),

'C': ['apple', 'banana', 'cherry', 'date', 'elderberry',


'fig', 'grape', 'honeydew', 'imbe', 'jackfruit'],
'D': np.random.choice([True, False], 10),

'E': pd.date_range('2023-01-01', periods=10)

df = pd.DataFrame(data_dict)

# Select two columns for plotting

x_column = 'A'

y_column = 'B'

# Scatter plot

plt.figure(figsize=(8, 6))
plt.scatter(df[x_column], df[y_column], color='blue',
label='Data Points')

plt.title(f'Scatter Plot of {y_column} vs {x_column}')

plt.xlabel(x_column)

plt.ylabel(y_column)

plt.legend()

plt.grid(True)

plt.show()

# Line plot

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

plt.plot(df[x_column], df[y_column], marker='o',


color='green', linestyle='-', linewidth=2, markersize=8,
label='Data Points')

plt.title(f'Line Plot of {y_column} vs {x_column}')

plt.xlabel(x_column)

plt.ylabel(y_column)

plt.legend()

plt.grid(True)

plt.show()
Output:

You might also like