Final Python Programming
Final Python Programming
II YEAR / I SEMESTER
LAB MANUAL
Prepared by
[Link], M.E,(PhD)
2. Demonstrate about Python data structures like Lists, Tuples, Sets and dictionaries
SAMPLE OUTPUT :
Enter the first number: 25
Enter the second number: 48
Enter the third number: 12
The largest number is: 48.0
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
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
SAMPLE OUTPUT
Prime numbers between 10 and 50:
11 13 17 19 23 29 31 37 41 43 47
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
RESULT:
TOTAL 25
SAMPLE OUTPUT
Before swapping: a = 5 , b = 10
After swapping: a = 10 , b = 5
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
print("Addition:", a + b) # 13
print("Subtraction:", a - b) # 7
print("Multiplication:", a * b) # 30
print("Division:", a / b) # 3.333...
print("Modulus:", a % b) # 1
print("Exponentiation:", a ** b) # 1000
print("Floor Division:", a // b) # 3
SAMPLE OUTPUT
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3.3333333333333335
Modulus: 1
Exponentiation: 1000
Floor Division: 3
2. Relational (Comparison) Operators
x = 5
y = 10
SAMPLE OUTPUT
x > y: False
x < y: True
x == y: False
x != y: True
x >= y: False
x <= y: True
3. Assignment Operators
Initial value: 5
After += 3: 8
After -= 2: 6
After *= 4: 24
After /= 6: 4.0
After %= 3: 1.0
4. Logical Operators
a = True
b = False
a and b: False
a or b: True
not a: False
5. Bitwise Operators
x = 6 # Binary: 110
y = 3 # Binary: 011
SAMPLE OUTPUT
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
5) Here’s a Python program to add and multiply complex numbers using the built-in complex type:
Aim:
# 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
# Input: Two complex numbers
complex1 = complex(3, 4) # Example: 3 + 4j
complex2 = complex(1, 2) # Example: 1 + 2j
# Perform addition and multiplication
sum_result = add_complex(complex1, complex2)
product_result = multiply_complex(complex1, complex2)
# Output the results
print(f"Addition of {complex1} and {complex2} = {sum_result}")
print(f"Multiplication of {complex1} and {complex2} = {product_result}")
Explanation:
1. Complex Numbers in Python: Python has a built-in complex type to
handle complex numbers. You can define a complex number as complex(real,
imaginary) or directly as a + bj.
2. Addition: Adding two complex numbers is straightforward using the +
operator.
3. Multiplication: Multiplying two complex numbers uses the * operator,
which adheres to the mathematical rules for complex multiplication.
This program is simple, efficient, and leverages Python's native support for complex
numbers.
SAMPLE OUTPUT
Addition of (3+4j) and (1+2j) = (4+6j)
Multiplication of (3+4j) and (1+2j) = (-5+10j)
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
II [Link] CST Python Programming Page 12 VIVA-VOCE 5
TOTAL 25
RESULT:
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
II [Link] CST Python Programming Page 13 RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
This program is simple, user-friendly, and works for any integer input!
Aim:
def calculate_stats(numbers):
"""
min_val = min(numbers)
max_val = max(numbers)
average_val = sum(numbers) / len(numbers)
return min_val, max_val, average_val
# Example usage
data = [10, 20, 30, 40, 50]
minimum, maximum, average = calculate_stats(data)
print(f"Original data: {data}")
print(f"Minimum value: {minimum}")
print(f"Maximum value: {maximum}")
print(f"Average value: {average}")
# Example with an empty list
empty_data = []
min_empty, max_empty, avg_empty = calculate_stats(empty_data)
print(f"\nStats for empty data: Min={min_empty}, Max={max_empty},
SAMPLE OUTPUT
Original data: [10, 20, 30, 40, 50]
Minimum value: 10
Maximum value: 50
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
RESULT:
TOTAL 25
Aim:
Args:
name (str): The name of the person to greet.
greeting (str, optional): The greeting message. Defaults to "Hello".
"""
message = f"{greeting}, {name}!"
print(message)
# Calling the function with only the required argument (using the default)
greet("Bob")
SAMPLE OUTPUT
Hi, Alice!
Hello, Bob!
Good morning, Charlie!
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
II [Link] CST Python Programming Page 15 RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
II.3.A program to find the length of a string without using any built-in library functions can be
implemented by iterating through the string and incrementing a counter for each character
encountered.
Aim:
def get_string_length(input_string):
"""
"""
count += 1
return count
# Example usage:
length = get_string_length(my_string)
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
II.4.A program to check if a substring is present in a given string can be implemented in various
programming languages using built-in string methods or operators.
def check_substring(main_string, sub_string):
"""
Checks if a substring is present in a main string.
Args:
main_string (str): The string to search within.
sub_string (str): The substring to search for.
Returns:
bool: True if the substring is found, False otherwise.
"""
else:
return False
# Example usage
substring1 = "world"
substring2 = "Python"
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
II.5.A Python program demonstrating list operations for addition (appending and extending),
insertion, and slicing is provided below.
Aim:
def perform_list_operations():
"""
"""
my_list.append(60)
my_list.extend(another_list)
# ii. Insertion
# iii. Slicing
sliced_list_1 = my_list[1:5]
sliced_list_2 = my_list[:4]
sliced_list_3 = my_list[5:]
copied_list = my_list[:]
perform_list_operations()
SAMPLE OUTPUT
Original list: [10, 20, 30, 40, 50]
After appending 60: [10, 20, 30, 40, 50, 60]
After extending with [70, 80]: [10, 20, 30, 40, 50, 60, 70, 80]
After inserting 25 at index 2: [10, 20, 25, 30, 40, 50, 60, 70, 80]
Sliced list (index 1 to 4): [20, 25, 30, 40]
Sliced list (beginning to index 3): [10, 20, 25, 30]
Sliced list (index 5 to end): [50, 60, 70, 80]
Copied list using slicing: [10, 20, 25, 30, 40, 50, 60, 70, 80]
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
[Link] following Python program demonstrates the use of five common built-in functions with a
given list: len(), max(), min(), sum(), and sorted().
Aim:
# Define a sample list
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
# Creating tuples
member1 = ('John', 25, '123 Street', 'ABC College')
member2 = ('Alice', 22, '456 Avenue', 'XYZ College')
# concatenating tuples
concatenated_tuple = member1 + member2
print(concatenated_tuple)
III.2. Write a program to count the number of vowels in a string (No control flow allowed)
# Using list comprehension to count vowels in a string
string = "example string"
vowel_count = len([char for char in string if char in 'aeiouAEIOU'])
print(vowel_count)
SAMPLE OUTPUT
4
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
def print_file_lines_reversed(filename):
"""
Args:
"""
try:
lines = [Link]()
reversed_lines = lines[::-1]
print([Link]())
except FileNotFoundError:
except Exception as e:
# Example usage:
[Link]("Line 1\n")
[Link]("Line 2\n")
[Link]("Line 3\n")
print_file_lines_reversed("[Link]")
SAMPLE OUTPUT
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
[Link] program to compute the number of characters, words and lines in a file.
Aim:
def print_file_lines_reversed(filename):
"""
Args:
"""
try:
lines = [Link]()
reversed_lines = lines[::-1]
print([Link]())
except FileNotFoundError:
except Exception as e:
# Example usage:
[Link]("Line 1\n")
[Link]("Line 2\n")
[Link]("Line 3\n")
print_file_lines_reversed("[Link]")
[Link] a program to create, display, append, insert and reverse the order of the items in
the array.
def array_operations():
# 1. Create an array (list in Python)
my_array = [10, 20, 30, 40, 50]
# 3. Append an item
my_array.append(60)
print(f"Array after appending 60: {my_array}")
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
"""
Args:
Returns:
A new matrix that is the sum of mat1 and mat2, or None if dimensions
don't match.
"""
rows = len(mat1)
cols = len(mat1[0])
for i in range(rows):
for j in range(cols):
return result
def transpose_matrix(mat):
"""
Transposes a matrix.
Args:
"""
rows = len(mat)
cols = len(mat[0])
for i in range(rows):
for j in range(cols):
result[j][i] = mat[i][j]
return result
"""
Args:
Returns:
"""
if len(mat1[0]) != len(mat2):
rows1 = len(mat1)
cols1 = len(mat1[0])
rows2 = len(mat2)
cols2 = len(mat2[0])
for i in range(rows1):
for j in range(cols2):
for k in range(cols1):
return result
# Example Usage:
if addition_SAMPLE OUTPUT
print("Matrix Addition:")
print(row)
else:
transpose_a = transpose_matrix(matrix_a)
print("\nMatrix A Transpose:")
print(row)
if multiplication_SAMPLE OUTPUT
print("\nMatrix Multiplication:")
print(row)
else:
SAMPLE OUTPUT
Matrix Addition:
[10, 10, 10]
[10, 10, 10]
[10, 10, 10]
Matrix A Transpose:
[1, 4, 7]
[2, 5, 8]
[3, 6, 9]
Matrix Multiplication:
[30, 24, 18]
[84, 69, 54]
[138, 114, 90]
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
import math
# Define a base class called Shape to represent a generic shape with methods
for calculating area and perimeter
class Shape:
def calculate_area(self):
pass
def calculate_perimeter(self):
pass
# Define a derived class called Circle, which inherits from the Shape class
class Circle(Shape):
[Link] = radius
# Calculate and return the area of the circle using the formula: π * r^2
def calculate_area(self):
# Calculate and return the perimeter of the circle using the formula: 2π
* r
def calculate_perimeter(self):
# Define a derived class called Rectangle, which inherits from the Shape
class
class Rectangle(Shape):
[Link] = length
[Link] = width
# Calculate and return the area of the rectangle using the formula:
length * width
def calculate_area(self):
# Calculate and return the perimeter of the rectangle using the formula:
2 * (length + width)
def calculate_perimeter(self):
# Define a derived class called Triangle, which inherits from the Shape class
class Triangle(Shape):
# Initialize the Triangle object with a base, height, and three side
lengths
[Link] = base
[Link] = height
self.side1 = side1
self.side2 = side2
self.side3 = side3
# Calculate and return the area of the triangle using the formula: 0.5 *
base * height
def calculate_perimeter(self):
# Example usage
# Create a Circle object with a given radius and calculate its area and
perimeter
r = 7
circle = Circle(r)
circle_area = circle.calculate_area()
circle_perimeter = circle.calculate_perimeter()
# Create a Rectangle object with given length and width and calculate its
area and perimeter
l = 5
w = 7
rectangle = Rectangle(l, w)
rectangle_area = rectangle.calculate_area()
rectangle_perimeter = rectangle.calculate_perimeter()
# Create a Triangle object with a base, height, and three side lengths, and
calculate its area and perimeter
base = 5
height = 4
s1 = 4
s2 = 3
s3 = 5
# Print the results for the Triangle
print("\nTriangle: Base =", base, " Height =", height, " side1 =", s1, "
side2 =", s2, " side3 =", s3)
triangle_area = triangle.calculate_area()
triangle_perimeter = triangle.calculate_perimeter()
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
def contains_nested_structure(data):
"""
"""
if isinstance(data, dict):
return True
return True
return True
return True
return False
# Example usage:
parsed_simple = [Link](json_string_simple)
parsed_array = [Link](json_string_with_array)
SAMPLE OUTPUT
'{"name": "Alice", "details": {"age": 30, "city": "New York"}}' contains complex
object: True
'{"name": "Bob", "age": 25}' contains complex object: False
'{"items": [1, 2, {"key": "value"}]}' contains complex object: True
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
list_data = [1, 2, 3, 4, 5]
array_from_list = [Link](list_data)
print(array_from_list)
print("Type:", type(array_from_list))
print("-" * 30)
array_from_tuple = [Link](tuple_data)
print(array_from_tuple)
print("Type:", type(array_from_tuple))
print("-" * 30)
array_2d_from_list = [Link](nested_list_data)
print(array_2d_from_list)
print("Shape:", array_2d_from_list.shape)
print("Type:", type(array_2d_from_list))
print("-" * 30)
array_3d_from_list = [Link](nested_list_3d)
print(array_3d_from_list)
print("Shape:", array_3d_from_list.shape)
print("Type:", type(array_3d_from_list))
SAMPLE OUTPUT
1-D Array from List:
[1 2 3 4 5]
Type: <class '[Link]'>
------------------------------
1-D Array from Tuple:
[10 20 30 40]
Type: <class '[Link]'>
------------------------------
2-D Array from Nested List:
[[1 2 3]
[4 5 6]]
Shape: (2, 3)
Type: <class '[Link]'>
------------------------------
3-D Array from Nested List:
[[[1 2]
[3 4]]
[[5 6]
[7 8]]]
Shape: (2, 2, 2)
Type: <class '[Link]'>
ACTUAL OUTPUT:
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
print(f"Original array:\n{arr}\n")
num_dimensions = [Link]
array_shape = [Link]
total_elements = [Link]
data_type = [Link]
print(f"\n1D array:\n{arr_1d}\n")
Original array:
[[1 2 3]
[4 5 6]]
SAMPLE OUTPUT
Number of dimensions (ndim): 2
Shape of the array (shape): (2, 3)
Total number of elements (size): 6
Data type of the elements (dtype): int64
1D array:
[10 20 30 40]
ACTUAL OUTPUT:
RESULT:
arr = [Link]([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])
# 1. Basic Slicing
slice1 = arr[2:6]
slice3 = arr[4:]
slice4 = arr[1:9:2]
# 2. Integer Indexing
element1 = arr[3]
# 3. Boolean Indexing
filtered_arr = arr[boolean_mask]
filtered_arr_even = arr[arr % 20 == 0]
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT:
"""
Analyzes an array to find its minimum, maximum, total sum, and cumulative
sum.
Args:
Returns:
"""
if not arr:
min_val = min(arr)
max_val = max(arr)
total_sum = sum(arr)
cumulative_sum_list = []
current_sum = 0
current_sum += num
cumulative_sum_list.append(current_sum)
# Example usage:
my_array = [1, 5, 2, 8, 3]
my_empty_array = []
min_val_empty, max_val_empty, total_sum_empty, cumulative_sum_empty =
analyze_array(my_empty_array)
SAMPLE OUTPUT
Original Array: [1, 5, 2, 8, 3]
Minimum Value: 1
Maximum Value: 8
Total Sum: 19
Cumulative Sum: [1, 6, 8, 16, 19]
DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25
RESULT: