0% found this document useful (0 votes)
4 views27 pages

r23 Python

The document contains programming exercises covering various topics in Python, including finding the largest number among three, displaying prime numbers, swapping numbers, demonstrating operators, handling complex numbers, and printing multiplication tables. It also includes functions with multiple return values, default arguments, string length calculations, substring checks, and list operations. Each section provides example code and expected output for better understanding.

Uploaded by

bslsdevi
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)
4 views27 pages

r23 Python

The document contains programming exercises covering various topics in Python, including finding the largest number among three, displaying prime numbers, swapping numbers, demonstrating operators, handling complex numbers, and printing multiplication tables. It also includes functions with multiple return values, default arguments, string length calculations, substring checks, and list operations. Each section provides example code and expected output for better understanding.

Uploaded by

bslsdevi
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/ 27

UNIT-1:

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


# Function to find the largest of three numbers
def find_largest(num1, num2, num3):
if num1 >= num2 and num1 >= num3:
return num1
elif num2 >= num1 and num2 >= num3:
return num2
else:
return num3

# Example input
number1 = 10
number2 = 25
number3 = 15
# Calling the function and printing the result
largest = find_largest(number1, number2, number3)
print("The largest number is:", largest)
Output :
The largest number is: 25

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


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

# Function to display prime numbers in an interval


def display_primes(start, end):
print(f"Prime numbers between {start} and {end} are:")
for num in range(start, end + 1):
if is_prime(num):
print(num, end=" ")

# Example interval
start_interval = 10
end_interval = 50

# Calling the function to display primes in the given range


display_primes(start_interval, end_interval)
Output:
Prime numbers between 10 and 50 are:
11 13 17 19 23 29 31 37 41 43 47

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


# Function to swap two numbers without using a temporary variable
def swap_numbers(a, b):
print(f"Before swapping: a = {a}, b = {b}")

# Swapping logic
a, b = b, a

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


return a, b

# Example numbers
num1 = 5
num2 = 10

# Swapping the numbers


swap_numbers(num1, num2)

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

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


i) Arithmetic Operators ii) Relational Operators iii) Assignment Operatorsiv)
Logical
Operators v) Bit wise Operators vi) Ternary Operator vii) Membership
Operatorsviii)
Identity Operators.
 Arithmetic Operators perform basic math operations.
 Relational Operators compare two values and return True or False.
 Assignment Operators are used to assign values and perform operations
in place.
 Logical Operators perform boolean logic (and, or, not).
 Bitwise Operators operate on binary numbers.
 Ternary Operator evaluates a condition and returns a result based on the
condition.
 Membership Operators check if a value is present in a sequence like lists.
 Identity Operators compare objects' memory locations (with is and is not).

# Demonstrating various operators in Python


# i) Arithmetic Operators
def arithmetic_operators(a, b):
print("Arithmetic Operators:")
print(f"{a} + {b} = {a + b}") # Addition
print(f"{a} - {b} = {a - b}") # Subtraction
print(f"{a} * {b} = {a * b}") # Multiplication
print(f"{a} / {b} = {a / b}") # Division
print(f"{a} % {b} = {a % b}") # Modulus
print(f"{a} ** {b} = {a ** b}") # Exponentiation
print(f"{a} // {b} = {a // b}") # Floor division
print()
# ii) Relational Operators
def relational_operators(a, b):
print("Relational Operators:")
print(f"{a} == {b} -> {a == b}") # Equal
print(f"{a} != {b} -> {a != b}") # Not equal
print(f"{a} > {b} -> {a > b}") # Greater than
print(f"{a} < {b} -> {a < b}") # Less than
print(f"{a} >= {b} -> {a >= b}") # Greater than or equal to
print(f"{a} <= {b} -> {a <= b}") # Less than or equal to
print()

# iii) Assignment Operators


def assignment_operators(a):
print("Assignment Operators:")
x=a
print(f"x = {x}") # Assignment
x += 5
print(f"x += 5 -> {x}") # Add and assign
x -= 3
print(f"x -= 3 -> {x}") # Subtract and assign
x *= 2
print(f"x *= 2 -> {x}") # Multiply and assign
x /= 2
print(f"x /= 2 -> {x}") # Divide and assign
x %= 4
print(f"x %= 4 -> {x}") # Modulus and assign
print()

# iv) Logical Operators


def logical_operators(a, b):
print("Logical Operators:")
print(f"{a} > 0 and {b} > 0 -> {a > 0 and b > 0}") # AND
print(f"{a} > 0 or {b} > 0 -> {a > 0 or b > 0}") # OR
print(f"not({a} > 0) -> {not(a > 0)}") # NOT
print()

# v) Bitwise Operators
def bitwise_operators(a, b):
print("Bitwise Operators:")
print(f"{a} & {b} = {a & b}") # Bitwise AND
print(f"{a} | {b} = {a | b}") # Bitwise OR
print(f"{a} ^ {b} = {a ^ b}") # Bitwise XOR
print(f"~{a} = {~a}") # Bitwise NOT
print(f"{a} << 1 = {a << 1}") # Bitwise left shift
print(f"{a} >> 1 = {a >> 1}") # Bitwise right shift
print()

# vi) Ternary Operator


def ternary_operator(a, b):
print("Ternary Operator:")
result = "a is greater" if a > b else "b is greater or equal"
print(f"Result of Ternary Operator: {result}")
print()

# vii) Membership Operators


def membership_operators():
print("Membership Operators:")
lst = [1, 2, 3, 4, 5]
print(f"Is 3 in list? -> {3 in lst}") # In
print(f"Is 6 not in list? -> {6 not in lst}") # Not in
print()

# viii) Identity Operators


def identity_operators():
print("Identity Operators:")
x = [1, 2, 3]
y = [1, 2, 3]
z=x
print(f"x is z -> {x is z}") # Identity (is)
print(f"x is y -> {x is y}") # Identity (is not)
print(f"x == y -> {x == y}") # Equality check
print()

# Example usage
a = 10
b=3

arithmetic_operators(a, b)
relational_operators(a, b)
assignment_operators(a)
logical_operators(a, b)
bitwise_operators(a, b)
ternary_operator(a, b)
membership_operators()
identity_operators()

Output:
Arithmetic Operators:
10 + 3 = 13
10 - 3 = 7
10 * 3 = 30
10 / 3 = 3.3333333333333335
10 % 3 = 1
10 ** 3 = 1000
10 // 3 = 3

Relational Operators:
10 == 3 -> False
10 != 3 -> True
10 > 3 -> True
10 < 3 -> False
10 >= 3 -> True
10 <= 3 -> False

Assignment Operators:
x = 10
x += 5 -> 15
x -= 3 -> 12
x *= 2 -> 24
x /= 2 -> 12.0
x %= 4 -> 0.0

Logical Operators:
10 > 0 and 3 > 0 -> True
10 > 0 or 3 > 0 -> True
not(10 > 0) -> False

Bitwise Operators:
10 & 3 = 2
10 | 3 = 11
10 ^ 3 = 9
~10 = -11
10 << 1 = 20
10 >> 1 = 5

Ternary Operator:
Result of Ternary Operator: a is greater

Membership Operators:
Is 3 in list? -> True
Is 6 not in list? -> True

Identity Operators:
x is z -> True
x is y -> False
x == y -> True

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


# Program to add and multiply complex numbers

# Function to add two complex numbers


def add_complex(c1, c2):
return c1 + c2

# Function to multiply two complex numbers


def multiply_complex(c1, c2):
return c1 * c2

# Example complex numbers


complex1 = complex(2, 3) # 2 + 3j
complex2 = complex(4, 5) # 4 + 5j
# Adding the complex numbers
sum_result = add_complex(complex1, complex2)
print(f"Sum of {complex1} and {complex2} is: {sum_result}")

# Multiplying the complex numbers


product_result = multiply_complex(complex1, complex2)
print(f"Product of {complex1} and {complex2} is: {product_result}")

Output:
Sum of (2+3j) and (4+5j) is: (6+8j)
Product of (2+3j) and (4+5j) is: (-7+22j)

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


# Function to print the multiplication table of a number
def multiplication_table(num, upto=10):
print(f"Multiplication Table for {num}:")
for i in range(1, upto + 1):
print(f"{num} x {i} = {num * i}")

# Input: number from user


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

# Call the function to print the multiplication table


multiplication_table(number)

Output:
Enter a number:
5
Multiplication Table for 5:
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

Unit – 2:
1. Write a program to define a function with multiple return values.
# Function to print the multiplication table of a number
def multiplication_table(num, upto=10):
print(f"Multiplication Table for {num}:")
for i in range(1, upto + 1):
print(f"{num} x {i} = {num * i}")

# Input: number from user


number = int(input("Enter a number: "))
# Call the function to print the multiplication table
multiplication_table(number)
Output:
Enter a number:
4
Multiplication Table for 4:
4x1=4
4x2=8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40

2. Write a program to define a function using default arguments.


# Function with default arguments
def greet(name, message="Hello"):
print(f"{message}, {name}!")

# Calling the function with and without the default argument


greet("Alice") # Uses the default message
greet("Bob", "Good morning") # Overrides the default message

Output:
Hello, Alice!
Good morning, Bob!

3. Write a program to find the length of the string without using any library
functions.
# Function to find the length of a string without using library functions
def string_length(s):
length = 0
for char in s:
length += 1
return length

# Example string
input_string = input("Enter a string: ")

# Call the function to get the length


length_of_string = string_length(input_string)

# Output the result


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

Output:
Enter a string:
hello
The length of the string 'hello' is: 5

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


# Function to check if a substring is present in a string
def is_substring_present(main_string, sub_string):
# Iterate over the main string to check for the substring
if sub_string in main_string:
return True
else:
return False

# Input: main string and substring from the user


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

# Check if the substring is present


if is_substring_present(main_string, sub_string):
print(f"The substring '{sub_string}' is present in '{main_string}'.")
else:
print(f"The substring '{sub_string}' is not present in '{main_string}'.")

Output:
Enter the main string:
welcome
Enter the substring:
come
The substring 'come' is present in 'welcome'.

Enter the main string:


welcome
Enter the substring:
came
The substring 'came' is not present in 'welcome'.

5. Write a program to perform the given operations on a list:


i. addition ii. Insertion iii. Slicing
# Function to demonstrate list operations: addition, insertion, and slicing
def list_operations():
# Initial list
my_list = [1, 2, 3, 4, 5]
print("Initial list:", my_list)

# i. Addition (concatenation)
# Adding another list to the initial list
additional_list = [6, 7, 8]
my_list += additional_list # or my_list.extend(additional_list)
print("After addition:", my_list)

# ii. Insertion
# Inserting an element at a specific position (index 2)
my_list.insert(2, 9) # Inserts 9 at index 2
print("After insertion of 9 at index 2:", my_list)

# iii. Slicing
# Slicing the list to get elements from index 2 to index 5
sliced_list = my_list[2:6] # Gets elements from index 2 to 5
print("Sliced list (from index 2 to 5):", sliced_list)

# Call the function to perform the operations


list_operations()

Output:
Initial list: [1, 2, 3, 4, 5]
After addition: [1, 2, 3, 4, 5, 6, 7, 8]
After insertion of 9 at index 2: [1, 2, 9, 3, 4, 5, 6, 7, 8]
Sliced list (from index 2 to 5): [9, 3, 4, 5]

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


# Sample list
my_list = [10, 20, 30, 40, 50]

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


length_of_list = len(my_list)
print(f"Length of the list: {length_of_list}")

# 2. sum() - Calculate the sum of all elements in the list


sum_of_list = sum(my_list)
print(f"Sum of the list: {sum_of_list}")

# 3. max() - Find the maximum element in the list


max_element = max(my_list)
print(f"Maximum element in the list: {max_element}")

# 4. min() - Find the minimum element in the list


min_element = min(my_list)
print(f"Minimum element in the list: {min_element}")

# 5. sorted() - Return a new sorted list from the original list


sorted_list = sorted(my_list)
print(f"Sorted list: {sorted_list}")

# Displaying the original list to show it is unchanged


print(f"Original list remains unchanged: {my_list}")

Output:

Length of the list: 5


Sum of the list: 150
Maximum element in the list: 50
Minimum element in the list: 10
Sorted list: [10, 20, 30, 40, 50]
Original list remains unchanged: [10, 20, 30, 40, 50]

Unit -3:
1. Write a program to create tuples (name, age, address, college) for at least
two
members and concatenate the tuples and print the concatenated tuples.
# Define tuples for two members

member1 = ("Alice", 22, "123 Main St, Springfield", "Springfield University")

member2 = ("Bob", 24, "456 Elm St, Springfield", "Springfield College")

# Concatenate the tuples

combined_members = member1 + member2

# Print the concatenated tuples

print("Concatenated Tuples:")

print(combined_members)

Output:

Concatenated Tuples:

('Alice', 22, '123 Main St, Springfield', 'Springfield University', 'Bob', 24, '456 Elm St, Springfield',
'Springfield College')

2. Write a program to count the number of vowels in a string (No control flow
allowed).
def count_vowels(input_string):

# Define vowels

vowels = "aeiouAEIOU"

# Use the sum and map functions to count vowels

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

# Example usage

input_string = "Hello, how are you?"

vowel_count = count_vowels(input_string)

print(f"Number of vowels: {vowel_count}")

Output:

Number of vowels: 7
3. Write a program to check if a given key exists in a dictionary or not.
def check_key_exists(dictionary, key):
return key in dictionary

# Example usage
my_dict = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}

key_to_check = 'age'

if check_key_exists(my_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:

The key 'age' exists in the dictionary.

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


def add_key_value(dictionary, key, value):
dictionary[key] = value
return dictionary

# Example usage
my_dict = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}

# Key-value pair to add


new_key = 'occupation'
new_value = 'Engineer'
# Add the new key-value pair
updated_dict = add_key_value(my_dict, new_key, new_value)

# Print the updated dictionary


print("Updated Dictionary:")
print(updated_dict)5. Write a program to sum all the items in a given dictionary.
Output

Updated Dictionary:

{'name': 'Alice', 'age': 25, 'city': 'New York', 'occupation': 'Engineer'}

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


# Function to sum all the values in a dictionary

def sum_dict_items(my_dict):

return sum(my_dict.values())

# Example dictionary

sample_dict = {'a': 10, 'b': 20, 'c': 30}

# Calling the function and printing the result

result = sum_dict_items(sample_dict)

print("The sum of all items in the dictionary is:", result)

Output:

The sum of all items in the dictionary is: 60

Unit-4:

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

Input: (input.txt)
Banana
apple
Cherry
date
Elderberry
fig
Grape

Output: (output.txt)
apple
banana
cherry
date
elderberry
fig
grape

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


def print_lines_in_reverse(input_file):
try:
# Open the file in read mode
with open(input_file, 'r') as file:
# Read all lines from the file
lines = file.readlines()

# Print each line in reverse order


for line in lines:
print(line.strip()[::-1]) # Reverse the line and remove any trailing
newline characters

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

# Example usage
input_filename = 'input.txt' # Replace with your input file path

print_lines_in_reverse(input_filename)

Input (input.txt):
Hello, World!

Output:
!dlroW ,olleH

3. Python program to compute the number of characters, words and lines in a


file.
def compute_file_stats(input_file):
try:
# Initialize counters
num_lines = 0
num_words = 0
num_characters = 0
# Open the file in read mode
with open(input_file, 'r') as file:
for line in file:
num_lines += 1 # Count lines
num_characters += len(line) # Count characters in the line
num_words += len(line.split()) # Count words in the line

# Print the 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"Error: The file '{input_file}' does not exist.")
except Exception as e:
print(f"An error occurred: {e}")

# Example usage
input_filename = 'input.txt' # Replace with your input file path

compute_file_stats(input_filename)

Input (input.txt):
Hello, World!
Python programming is fun.
This is a sample text file.

Output:
Number of lines: 3
Number of words: 10
Number of characters: 58

4. Write a program to create, display, append, insert and reverse the order of
the items
in the array.

def array_operations():
# Create an array (list in Python)
my_array = [1, 2, 3, 4, 5]
print("Initial array:", my_array)

# Display the items in the array


print("Displaying items in the array:")
for item in my_array:
print(item)

# Append an item to the array


my_array.append(6) # Append 6 to the array
print("Array after appending 6:", my_array)

# Insert an item at a specific position (index 2)


my_array.insert(2, 99) # Insert 99 at index 2
print("Array after inserting 99 at index 2:", my_array)

# Reverse the order of the items in the array


my_array.reverse()
print("Array after reversing:", my_array)

# Call the function to perform the operations


array_operations()

Output:
Initial array: [1, 2, 3, 4, 5]
Displaying items in the array:
1
2
3
4
5
Array after appending 6: [1, 2, 3, 4, 5, 6]
Array after inserting 99 at index 2: [1, 2, 99, 3, 4, 5, 6]
Array after reversing: [6, 5, 4, 3, 99, 2, 1]

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


def add_matrices(matrix_a, matrix_b):
"""Add two matrices."""
result = []
for i in range(len(matrix_a)):
row = []
for j in range(len(matrix_a[0])):
row.append(matrix_a[i][j] + matrix_b[i][j])
result.append(row)
return result

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

def multiply_matrices(matrix_a, matrix_b):


"""Multiply two matrices."""
result = []
for i in range(len(matrix_a)):
row = []
for j in range(len(matrix_b[0])):
product = sum(matrix_a[i][k] * matrix_b[k][j] for k in
range(len(matrix_b)))
row.append(product)
result.append(row)
return result

# Example usage
matrix_a = [
[1, 2, 3],
[4, 5, 6]
]

matrix_b = [
[7, 8, 9],
[10, 11, 12]
]

# Adding the matrices


added_matrices = add_matrices(matrix_a, matrix_b)
print("Added Matrices:")
for row in added_matrices:
print(row)

# Transposing matrix A
transposed_matrix_a = transpose_matrix(matrix_a)
print("\nTransposed Matrix A:")
for row in transposed_matrix_a:
print(row)

# Multiplying the matrices


# Note: Matrix A should have the same number of columns as Matrix B has rows
matrix_b_for_multiplication = [
[7, 10],
[8, 11],
[9, 12]
]

multiplied_matrices = multiply_matrices(matrix_a, matrix_b_for_multiplication)


print("\nMultiplied Matrices:")
for row in multiplied_matrices:
print(row)

Output:

Added Matrices:
[8, 10, 12]
[14, 16, 18]

Transposed Matrix A:
[1, 4]
[2, 5]
[3, 6]

Multiplied Matrices:
[50, 68]
[122, 167]

6. Write a Python program to create a class that represents a shape. Include


methods to calculate its area and perimeter. Implement subclasses for different
shapes like circle,
triangle, and square.
import math
# Base class
class Shape:
def area(self):
raise NotImplementedError("This method should be overridden in
subclasses.")
def perimeter(self):
raise NotImplementedError("This method should be overridden in
subclasses.")
# Subclass for Circle
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

# Subclass for Triangle


class Triangle(Shape):
def __init__(self, base, height, side_a, side_b):
self.base = base
self.height = height
self.side_a = side_a
self.side_b = side_b
def area(self):
return 0.5 * self.base * self.height
def perimeter(self):
return self.base + self.side_a + self.side_b
# Subclass for Square
class Square(Shape):
def __init__(self, side_length):
self.side_length = side_length
def area(self):
return self.side_length ** 2
def perimeter(self):
return 4 * self.side_length
# Example usage
def main():
# Create a Circle
circle = Circle(radius=5)
print(f"Circle: Area = {circle.area():.2f}, Perimeter = {circle.perimeter():.2f}")
# Create a Triangle
triangle = Triangle(base=5, height=4, side_a=3, side_b=4)
print(f"Triangle: Area = {triangle.area():.2f}, Perimeter =
{triangle.perimeter():.2f}")
# Create a Square
square = Square(side_length=4)
print(f"Square: Area = {square.area():.2f}, Perimeter =
{square.perimeter():.2f}")
if __name__ == "__main__":
main()
Output:-
Circle: Area = 78.54, Perimeter = 31.42
Triangle: Area = 10.00, Perimeter = 12.00
Square: Area = 16.00, Perimeter = 16.00
Unit-5:
1. Python program to check whether a JSON string contains complex object or
not.

import json

def is_complex_object(obj):
"""Check if the given object is a complex object."""
if isinstance(obj, dict):
return True # It's a complex object if it's a dictionary
elif isinstance(obj, list):
return any(is_complex_object(item) for item in obj) # Check if any item in
the list is complex
return False # Not a complex object (it's a string, number, etc.)

def check_json_complexity(json_string):
"""Check if a JSON string contains complex objects."""
try:
parsed_json = json.loads(json_string) # Parse the JSON string
if is_complex_object(parsed_json):
print("The JSON string contains complex objects.")
else:
print("The JSON string does not contain complex objects.")
except json.JSONDecodeError:
print("Invalid JSON string.")

# Example JSON strings


json_string_1 = '{"name": "Alice", "age": 30, "address": {"city": "Wonderland",
"zip": "12345"}}'
json_string_2 = '{"name": "Bob", "age": 25}'

# Check the complexity of the JSON strings


check_json_complexity(json_string_1) # Contains complex object (address)
check_json_complexity(json_string_2) # Does not contain complex object

Output:
The JSON string contains complex objects.
The JSON string does not contain complex objects.

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


function.
import numpy as np

def demonstrate_numpy_array_creation():
# Creating a 1D NumPy array using array() function
one_d_array = np.array([1, 2, 3, 4, 5])
print("1D Array:")
print(one_d_array)

# Creating a 2D NumPy array using array() function


two_d_array = np.array([[1, 2, 3], [4, 5, 6]])
print("\n2D Array:")
print(two_d_array)

# Creating a 3D NumPy array using array() function


three_d_array = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print("\n3D Array:")
print(three_d_array)
# Demonstrating the shape of the arrays
print("\nShape of 1D Array:", one_d_array.shape)
print("Shape of 2D Array:", two_d_array.shape)
print("Shape of 3D Array:", three_d_array.shape)

# Demonstrating the data type of the arrays


print("\nData type of 1D Array:", one_d_array.dtype)
print("Data type of 2D Array:", two_d_array.dtype)
print("Data type of 3D Array:", three_d_array.dtype)

if __name__ == "__main__":
demonstrate_numpy_array_creation()

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]]]

Shape of 1D Array: (5,)


Shape of 2D Array: (2, 3)
Shape of 3D Array: (2, 2, 2)

Data type of 1D Array: int64


Data type of 2D Array: int64
Data type of 3D Array: int64

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

import numpy as np

def demonstrate_array_attributes():
# Creating a 1D NumPy array
one_d_array = np.array([1, 2, 3, 4, 5])

# Creating a 2D NumPy array


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

# Creating a 3D NumPy array


three_d_array = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
# Displaying attributes for 1D array
print("1D Array:")
print("Array:", one_d_array)
print("Number of dimensions (ndim):", one_d_array.ndim)
print("Shape:", one_d_array.shape)
print("Size (number of elements):", one_d_array.size)
print("Data type (dtype):", one_d_array.dtype)
print()

# Displaying attributes for 2D array


print("2D Array:")
print("Array:\n", two_d_array)
print("Number of dimensions (ndim):", two_d_array.ndim)
print("Shape:", two_d_array.shape)
print("Size (number of elements):", two_d_array.size)
print("Data type (dtype):", two_d_array.dtype)
print()

# Displaying attributes for 3D array


print("3D Array:")
print("Array:\n", three_d_array)
print("Number of dimensions (ndim):", three_d_array.ndim)
print("Shape:", three_d_array.shape)
print("Size (number of elements):", three_d_array.size)
print("Data type (dtype):", three_d_array.dtype)

if __name__ == "__main__":
demonstrate_array_attributes()

Output:
1D Array:
Array: [1 2 3 4 5]
Number of dimensions (ndim): 1
Shape: (5,)
Size (number of elements): 5
Data type (dtype): int64

2D Array:
Array:
[[1 2 3]
[4 5 6]]
Number of dimensions (ndim): 2
Shape: (2, 3)
Size (number of elements): 6
Data type (dtype): int64

3D Array:
Array:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Number of dimensions (ndim): 3
Shape: (2, 2, 2)
Size (number of elements): 8
Data type (dtype): int64

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


import numpy as np

def demonstrate_indexing_and_slicing():
# Creating a 2D NumPy array
array = np.array([[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]])

print("Original Array:")
print(array)
print()

# Basic Slicing
print("Basic Slicing:")
# Slicing to get the first two rows and first three columns
sliced_array = array[0:2, 0:3] # Get rows 0 and 1, and columns 0, 1, 2
print(sliced_array)
print()

# Integer Indexing
print("Integer Indexing:")
# Getting specific elements using integer indexing
# Get elements (0,1) and (1,2) which are 2 and 7
integer_indexed = array[[0, 1], [1, 2]]
print("Elements at (0,1) and (1,2):", integer_indexed)
print()

# Boolean Indexing
print("Boolean Indexing:")
# Create a boolean array where elements greater than 6 are True
boolean_mask = array > 6
print("Boolean Mask (array > 6):")
print(boolean_mask)

# Using the boolean mask to get elements greater than 6


filtered_array = array[boolean_mask]
print("Elements greater than 6:")
print(filtered_array)

if __name__ == "__main__":
demonstrate_indexing_and_slicing()
Output:
Original Array:
[[ 1 2 3 4]
[ 5 6 7 8]
[ 9 10 11 12]]

Basic Slicing:
[[1 2 3]
[5 6 7]]

Integer Indexing:
Elements at (0,1) and (1,2): [2 7]

Boolean Indexing:
Boolean Mask (array > 6):
[[False False False False]
[False False True True]
[ True True True True]]
Elements greater than 6:
[ 7 8 9 10 11 12]

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


import numpy as np

def demonstrate_array_operations():
# Creating a NumPy array
array = np.array([10, 20, 30, 40, 50])

# Finding the minimum value


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

# Finding the maximum value


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

# Finding the sum of the array


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

# Finding the cumulative sum of the array


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

if __name__ == "__main__":
demonstrate_array_operations()

Output:
Minimum value: 10
Maximum value: 50
Sum of the array: 150
Cumulative sum of the array: [ 10 30 60 100 150]

6. Create a dictionary with at least five keys and each key represent value as a
list where
this list contains at least ten values and convert this dictionary as a pandas data
frame
and explore the data through the data frame as follows:
a) Apply head () function to the pandas data frame
b) Perform various data selection operations on Data Frame

import pandas as pd

# Creating a dictionary with five keys, each key having a list of ten values
data_dict = {
'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]
}

# Converting the dictionary to a Pandas DataFrame


df = pd.DataFrame(data_dict)

# Displaying the DataFrame


print("DataFrame:")
print(df)

# a) Applying head() function to the DataFrame


print("\nHead of the DataFrame:")
print(df.head()) # Display the first 5 rows of the DataFrame

# b) Various data selection operations on DataFrame


print("\nSelecting a single column (B):")
print(df['B'])

print("\nSelecting multiple columns (A and C):")


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

print("\nSelecting rows based on conditions (values in A greater than 5):")


print(df[df['A'] > 5])

print("\nSelecting specific rows (first three rows):")


print(df.iloc[:3]) # Selecting the first three rows

print("\nSelecting specific rows and columns (rows 1 to 4 of column B and D):")


print(df.loc[1:4, ['B', 'D']]) # Selecting rows 1 to 4 of columns B and D

Output:
DataFrame:
A B C D E
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
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

Head of the DataFrame:


A B C D E
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

Selecting a single column (B):


0 11
1 12
2 13
3 14
4 15
5 16
6 17
7 18
8 19
9 20
Name: B, dtype: int64

Selecting multiple columns (A and C):


A C
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

Selecting rows based on conditions (values in A greater than 5):


A B C D E
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

Selecting specific rows (first three rows):


A B C D E
0 1 11 21 31 41
1 2 12 22 32 42
2 3 13 23 33 43

Selecting specific rows and columns (rows 1 to 4 of column B and D):


B D
1 12 32
2 13 33
3 14 34
4 15 35

7. Select any two columns from the above data frame, and observe the change
in one
attribute with respect to other attribute with scatter and plot operations in
matplotlib.
import pandas as pd

import matplotlib.pyplot as plt

# Creating a dictionary with five keys, each key having a list of ten values

data_dict = {

'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]

# Converting the dictionary to a Pandas DataFrame

df = pd.DataFrame(data_dict)

# Selecting two columns for scatter plot

x = df['A'] # Independent variable

y = df['B'] # Dependent variable


# Creating a scatter plot

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

plt.scatter(x, y, color='blue', label='Data Points')

plt.title('Scatter Plot of B vs A')

plt.xlabel('Column A')

plt.ylabel('Column B')

plt.grid()

plt.legend()

plt.show()

Output:

You might also like