0% found this document useful (0 votes)
5 views46 pages

Final Python Programming

The document is a lab manual for a Python Programming skill enhancement course for the academic year 2025-26. It outlines course objectives, provides guidelines for writing Python code, and includes a detailed index of experiments and programming tasks for students. The manual emphasizes best practices in coding, such as readability, meaningful naming, and regular testing, while also listing various programming exercises to reinforce learning.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views46 pages

Final Python Programming

The document is a lab manual for a Python Programming skill enhancement course for the academic year 2025-26. It outlines course objectives, provides guidelines for writing Python code, and includes a detailed index of experiments and programming tasks for students. The manual emphasizes best practices in coding, such as readability, meaningful naming, and regular testing, while also listing various programming exercises to reinforce learning.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Academic Year 2025-26

PYTHON PROGRAMMING (SKILL ENHANCEMENT COURSE)

II YEAR / I SEMESTER

Subject Code 23CTCTS3080

LAB MANUAL

Prepared by

[Link], M.E,(PhD)

Assistant Professor / CST

Course Objectives: The main objectives of the course are to

1. Introduce core programming concepts of Python programming language.

2. Demonstrate about Python data structures like Lists, Tuples, Sets and dictionaries

3. Implement Functions, Modules and Regular Expressions in Python Programming and to


create practical and contemporary applications using these.

II [Link] CST Python Programming Page 1


INSTUCTIONS

Do,s and Don’ts

Do's of Python Programming:


 Write Readable Code:
Python's syntax is designed to be clear and easy to understand. Prioritize code that is easy for both
humans and machines to read.
 Use Meaningful Variable and Function Names:
Choose names that clearly indicate what the variable or function represents. This improves code
maintainability and reduces confusion.
 Comment Your Code:
Add comments to explain complex logic, algorithm choices, or any non-obvious parts of your code. This
is especially helpful for collaborative projects and for future reference.
 Follow PEP 8 Style Guide:
Adhere to the official Python style guide (PEP 8) for consistent formatting and readability.
 Use Docstrings:
For functions and modules, write docstrings to explain their purpose, parameters, and return values.
 Embrace Pythonic Code:
Learn and utilize common Python idioms and data structures to write concise and efficient code.
 Test Your Code:
Write unit tests to ensure your code functions as expected and to catch errors early in the development
process.
 Keep Learning:
Python is constantly evolving. Stay up-to-date with the latest documentation, libraries, and best
practices.
 Practice Regularly:
Consistent practice is crucial for improving your Python skills.
 Seek Help and Collaborate:
Don't be afraid to ask for help when you're stuck, and participate in code reviews to learn from others.

II [Link] CST Python Programming Page 2


Don'ts of Python Programming:
 Don't Write Unclear Code: Avoid overly complex or ambiguous code that is difficult to understand.
 Don't Use Short or Confusing Variable Names: Avoid single-letter variable names (except in very
specific cases) and choose names that clearly convey the variable's purpose.
 Don't Ignore Security Practices: Validate user inputs, use secure libraries, and protect sensitive
information.
 Don't Over-Engineer Solutions: Keep your code simple and efficient. Avoid unnecessary
complexity.
 Don't Isolate Yourself: Engage with the Python community, participate in discussions, and
collaborate with other developers.
 Don't Skip Learning Core Concepts: A strong foundation in Python fundamentals is essential for
more advanced programming.
 Don't Rely on Magic Numbers: Use named constants instead of hardcoding numbers directly into
your code.
 Don't Neglect Error Handling: Implement proper error handling to prevent your code from crashing
due to unexpected situations.
 Don't Ignore Documentation: Refer to the official Python documentation and other reputable
resources to clarify concepts and usage.
 Don't Copy Code Without Understanding: Always try to understand the code you are using, even if
you are borrowing it from someone else.

II [Link] CST Python Programming Page 3


INDEX

[Link] Date Name of the Experiment MARKS( ) Signature

I.1 Write a program to find the largest


2/08/25
element among three Numbers.
2 Write a Program to display all prime
2/08/25
numbers within an interval
3 Write a program to swap two
9/08/25 numbers without using a temporary
variable.
4 Demonstrate the following
9/08/25 Operators in Python with suitable
examples.
5 Arithmetic Operators ii) Relational
Operators iii) Assignment Operators
iv) Logical Operators v) Bit wise
23/08/25
Operators vi) Ternary Operator vii)
Membership Operators viii) Identity
Operators
6 Write a program to add and multiply
23/08/25
complex numbers
II.1 Write a program to print
30/8/25 multiplication table of a given
number.
2 Write a program to define a function
30/08/25
with multiple return values
3 Write a program to define a function
6/09/25
using default arguments
4 Write a program to find the length
6/09/25 of the string without using any
library functions
5 Write a program to check if the
13/09/25 substring is present in a given string
or not
6 Write a program to perform the
13/09/25 given operations on a list: Addition
ii. Insertion iii. Slicing
7. Write a program to perform any 5
20/09/25
built-in functions by taking any list.
III.1 Write a program to create tuples
(name, age, address, college) for at
20/09/25 least two members and concatenate
the tuples and print the
concatenated tuples.
2 11/10/25 Write a program to count the
number of vowels in a string (No

II [Link] CST Python Programming Page 4


control flow allowed).
3 Write a program to check if a given
11/10/25
key exists in a dictionary or not.
4 11/10/25 Write a program to add a new key-
value pair to an existing dictionary.
5 25/10/25 Write a program to sum all the
items in a given dictionary.
IV.1 25/10/25 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
2 25/10/25 Python program to print each line of
a file in reverse order.
3 25/10/25 Python program to compute the
number of characters, words and
lines in a file
4 Write a program to create, display,
1/11/25 append, insert and reverse the order
of the items in the array.
5 Write a program to add, transpose
1/11/25
and multiply two matrices
6 Write a Python program to create a
class that represents a shape.
Include methods to calculate its area
8/11/25
and perimeter. Implement
subclasses for different shapes like
circle, triangle, and square.
V.1 Python program to check whether a
8/11/25 JSON string contains complex object
or not.
2 Python Program to demonstrate
15/11/25 NumPy arrays creation using array ()
function.
3 Python program to demonstrate use
15/11/25
of ndim, shape, size, dtype
4 Python program to demonstrate
22/11/25 basic slicing, integer and Boolean
indexing
5 Python program to find min, max,
22/11/25
sum, cumulative sum of array

II [Link] CST Python Programming Page 5


UNIT-I:Intoduction
1.1 Python program to find the largest element among three numbers:
Aim:
# Function to find the largest number
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

# Input from the user


num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
num3 = float(input("Enter the third number: "))

# Find and display the largest number


largest = find_largest(num1, num2, num3)
print(f"The largest number is: {largest}")
This program:
1. Accepts three numbers as input from the user.
2. Compares the numbers using conditional statements.
3. Outputs the largest number.
It's simple, efficient, and user-friendly!

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:

II [Link] CST Python Programming Page 6


2) Here is a Python program to display all prime numbers within a given interval:
Aim:

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

def display_primes(start, end):


print(f"Prime numbers between {start} and {end}:")
for number in range(start, end + 1):
if is_prime(number):
print(number, end=" ")
print()
# Example usage
start_interval = 10
end_interval = 50
display_primes(start_interval, end_interval)
Explanation:
1. is_prime Function: Checks if a number is prime by testing divisibility
up to the square root of the number.
2. display_primes Function: Iterates through the interval and prints all
prime numbers.
3. Example Usage: Modify start_interval and end_interval to set your
desired range.
This program is efficient and easy to adapt for different intervals.

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

II [Link] CST Python Programming Page 7


3) Here is a Python program to swap two numbers without using a temporary variable:
Aim:

# Method 1: Using arithmetic operations


a = 5
b = 10

print("Before swapping: a =", a, ", b =", b)

# Swap without a temporary variable


a = a + b
b = a - b
a = a - b

print("After swapping: a =", a, ", b =", b)

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:

II [Link] CST Python Programming Page 8


4) Here’s a demonstration of the requested Python operations with suitable examples:
Aim:
1. Arithmetic Operators
a = 10
b = 3

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

print("x > y:", x > y) # False


print("x < y:", x < y) # True
print("x == y:", x == y) # False
print("x != y:", x != y) # True
print("x >= y:", x >= y) # False
print("x <= y:", x <= y) # True

SAMPLE OUTPUT

x > y: False
x < y: True
x == y: False
x != y: True
x >= y: False
x <= y: True
3. Assignment Operators

II [Link] CST Python Programming Page 9


num = 5
print("Initial value:", num) # 5

num += 3 # Equivalent to num = num + 3


print("After += 3:", num) # 8

num -= 2 # Equivalent to num = num - 2


print("After -= 2:", num) # 6

num *= 4 # Equivalent to num = num * 4


print("After *= 4:", num) # 24

num /= 6 # Equivalent to num = num / 6


print("After /= 6:", num) # 4.0

num %= 3 # Equivalent to num = num % 3


print("After %= 3:", num) # 1.0
SAMPLE OUTPUT

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

print("a and b:", a and b) # False


print("a or b:", a or b) # True
print("not a:", not a) # False
SAMPLE OUTPUT

a and b: False
a or b: True
not a: False

5. Bitwise Operators
x = 6 # Binary: 110
y = 3 # Binary: 011

print("Bitwise AND:", x & y) # 2 (Binary: 010)


print("Bitwise OR:", x | y) # 7 (Binary: 111)
print("Bitwise XOR:", x ^ y) # 5 (Binary: 101)
print("Bitwise NOT:", ~x) # -7 (Inverts bits)
print("Left Shift:", x << 1) # 12 (Binary: 1100)
print("Right Shift:", x >> 1) # 3 (Binary: 011)

SAMPLE OUTPUT

II [Link] CST Python Programming Page 10


Bitwise AND: 2
Bitwise OR: 7
Bitwise XOR: 5
Bitwise NOT: -7
Left Shift: 12
Right Shift: 3
6. Ternary Operator
a = 10
b = 20
max_value = a if a > b else b
print("Maximum value:", max_value) # 20
SAMPLE OUTPUT
Maximum value: 20
7. Membership Operators
my_list = [1, 2, 3, 4, 5]
print("3 in my_list:", 3 in my_list) # True
print("10 not in my_list:", 10 not in my_list) # True
SAMPLE OUTPUT
3 in my_list: True
10 not in my_list: True
8. Identity Operators
x = [1, 2, 3]
y = [1, 2, 3]
z = x
print("x is z:", x is z) # True (same object)
print("x is y:", x is y) # False (different objects)
print("x is not y:", x is not y) # True
Each example demonstrates the respective operator in a clear and concise manner. Let me know if
you'd like further clarification!
SAMPLE OUTPUT
x is z: True
x is y: False
x is not y: True

ACTUAL OUTPUT:

DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25

II [Link] CST Python Programming Page 11


RESULT:

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:

6) Here’s a Python program to print the multiplication table of a given number:


Aim:

# Program to print the multiplication table of a given number

# Input from the user


number = int(input("Enter the number to print its multiplication table: "))

# Printing the multiplication table


print(f"\nMultiplication Table for {number}:\n")
for i in range(1, 11): # Loop from 1 to 10
print(f"{number} x {i} = {number * i}")
Example Output:
If the user inputs 5, the output will be:
Enter the number to print its multiplication table: 5
SAMPLE OUTPUT:
Multiplication Table for 5:
5 x 1 = 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

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!

UNIT-II: Functions Strings and Lists


[Link] program demonstrating a function with multiple return values using a tuple:

Aim:

def calculate_stats(numbers):
"""

Calculates the minimum, maximum, and average of a list of numbers.


Args:
numbers (list): A list of numerical values.
Returns:
tuple: A tuple containing (min_value, max_value, average_value).
"""
if not numbers:
return None, None, None # Handle empty list case

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

II [Link] CST Python Programming Page 14


Average value: 30.0

Stats for empty data: Min=None, Max=None, Avg=None


ACTUAL OUTPUT:

DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
RESULT:
TOTAL 25

[Link] a program to define a function using default arguments.

Aim:

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


"""
This function greets a person with a customizable greeting.

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 both arguments (overriding the default)


greet("Alice", "Hi")

# Calling the function with only the required argument (using the default)
greet("Bob")

# Calling the function with a different default value


greet("Charlie", "Good morning")

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

"""

Calculates the length of a string without using built-in functions like


len().

"""

II [Link] CST Python Programming Page 16


count = 0

for char in input_string:

count += 1

return count

# Example usage:

my_string = "Hello, World!"

length = get_string_length(my_string)

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


SAMPLE OUTPUT
The length of 'Hello, World!' is: 13

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.
"""

II [Link] CST Python Programming Page 17


if sub_string in main_string:
return True

else:

return False

# Example usage

string1 = "Hello, world!"

substring1 = "world"

substring2 = "Python"

print(f"Is '{substring1}' in '{string1}'? {check_substring(string1,


substring1)}")

print(f"Is '{substring2}' in '{string1}'? {check_substring(string1, substring2)}")


SAMPLE OUTPUT
Is 'world' in 'Hello, world!'? True
Is 'Python' in 'Hello, world!'? False

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

"""

Demonstrates addition (append/extend), insertion, and slicing operations


on a Python list.

"""

II [Link] CST Python Programming Page 18


my_list = [10, 20, 30, 40, 50]

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

# i. Addition (Appending and Extending)

# Appending a single element

my_list.append(60)

print(f"After appending 60: {my_list}")

# Extending with multiple elements from an iterable

another_list = [70, 80]

my_list.extend(another_list)

print(f"After extending with [70, 80]: {my_list}")

# ii. Insertion

# Inserting an element at a specific index

my_list.insert(2, 25) # Inserts 25 at index 2

print(f"After inserting 25 at index 2: {my_list}")

# iii. Slicing

# Get a sublist from index 1 to 4 (exclusive of 5)

sliced_list_1 = my_list[1:5]

print(f"Sliced list (index 1 to 4): {sliced_list_1}")

# Get a sublist from the beginning to index 3 (exclusive)

sliced_list_2 = my_list[:4]

print(f"Sliced list (beginning to index 3): {sliced_list_2}")

# Get a sublist from index 5 to the end

sliced_list_3 = my_list[5:]

print(f"Sliced list (index 5 to end): {sliced_list_3}")

II [Link] CST Python Programming Page 19


# Create a shallow copy of the entire list using slicing

copied_list = my_list[:]

print(f"Copied list using slicing: {copied_list}")

# Execute the function to perform the operations

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

my_list = [10, 5, 20, 15, 8, 25]

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

# 1. len(): Returns the number of items in a list.


list_length = len(my_list)
print(f"Length of the list (len()): {list_length}")
# 2. max(): Returns the largest item in an iterable.
maximum_value = max(my_list)

II [Link] CST Python Programming Page 20


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

# 3. min(): Returns the smallest item in an iterable.


minimum_value = min(my_list)
print(f"Minimum value in the list (min()): {minimum_value}")
# 4. sum(): Returns the sum of all items in an iterable.
total_sum = sum(my_list)
print(f"Sum of all elements in the list (sum()): {total_sum}")
# 5. sorted(): Returns a new sorted list from the items in an iterable.
sorted_list = sorted(my_list)
print(f"Sorted list (sorted()): {sorted_list}")
SAMPLE OUTPUT
Original list: [10, 5, 20, 15, 8, 25]
Length of the list (len()): 6
Maximum value in the list (max()): 25
Minimum value in the list (min()): 5
Sum of all elements in the list (sum()): 83
Sorted list (sorted()): [5, 8, 10, 15, 20, 25]

ACTUAL OUTPUT:

DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25

RESULT:

UNIT-III: Dictionaries& Tuples and Sets


1a. Program to create tuples (name, age, address, college) for at least two members

# 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)

II [Link] CST Python Programming Page 21


SAMPLE OUTPUT
('John', 25, '123 Street', 'ABC College', 'Alice', 22, '456 Avenue', 'XYZ College')

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

III.3. Write a program to check if a given key exists in a dictionary or not.


# Creating a sample dictionary
sample_dict = {'a': 1, 'b': 2, 'c': 3}

# Checking if a key exists


key_to_check = 'b'
key_exists = key_to_check in sample_dict
print(key_exists)
SAMPLE OUTPUT
True

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


# Existing dictionary
existing_dict = {'a': 1, 'b': 2}
# Adding a new key-value pair
existing_dict['c'] = 3
print(existing_dict)
SAMPLE OUTPUT
{'a': 1, 'b': 2, 'c': 3}

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


# Given dictionary
given_dict = {'a': 100, 'b': 200, 'c': 300}

# Summing all items


total_sum = sum(given_dict.values())
print(total_sum)
SAMPLE OUTPUT
600

II [Link] CST Python Programming Page 22


ACTUAL OUTPUT:

DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25

RESULT:

UNIT-IV: Files & Object-Oriented Programming


IV. 1. Python program to print each line of a file in reverse order,
Aim:
Follow these steps:
 Open the file:
Use with open('[Link]', 'r') as file: to open the file in read mode. This ensures the file is properly
closed even if errors occur.
 Read all lines:

II [Link] CST Python Programming Page 23


Use readlines() to read all lines from the file and store them as a list of strings. Each string in the list will
represent a line from the file, including the newline character \n.
 Reverse the list of lines:
Use list slicing [::-1] to create a reversed copy of the list of lines. This efficiently reverses the order of
the lines without modifying the original list in place.
 Print each reversed line:
Iterate through the reversed list and print each line. Use strip() or rstrip() to remove any trailing
whitespace, including the newline character, if desired, to prevent double newlines when printing.

def print_file_lines_reversed(filename):

"""

Reads a file and prints each line in reverse order.

Args:

filename (str): The path to the text file.

"""

try:

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

lines = [Link]()

# Reverse the list of lines

reversed_lines = lines[::-1]

print(f"Contents of '{filename}' in reverse line order:")

for line in reversed_lines:

# Use rstrip() to remove trailing whitespace, including


newline characters

print([Link]())

except FileNotFoundError:

print(f"Error: The file '{filename}' was not found.")

except Exception as e:

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

# Example usage:

# Create a dummy file for demonstration

II [Link] CST Python Programming Page 24


with open("[Link]", "w") as f:

[Link]("Line 1\n")

[Link]("Line 2\n")

[Link]("Line 3\n")

print_file_lines_reversed("[Link]")

SAMPLE OUTPUT

Contents of '[Link]' in reverse line order:


Line 3
Line 2
Line 1

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

"""

II [Link] CST Python Programming Page 25


Reads a file and prints each line in reverse order.

Args:

filename (str): The path to the text file.

"""

try:

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

lines = [Link]()

# Reverse the list of lines

reversed_lines = lines[::-1]

print(f"Contents of '{filename}' in reverse line order:")

for line in reversed_lines:

# Use rstrip() to remove trailing whitespace, including


newline characters

print([Link]())

except FileNotFoundError:

print(f"Error: The file '{filename}' was not found.")

except Exception as e:

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

# Example usage:

# Create a dummy file for demonstration

with open("[Link]", "w") as f:

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

II [Link] CST Python Programming Page 26


print(f"Original Array: {my_array}")

# 2. Display the array


print(f"Displaying Array: {my_array}")

# 3. Append an item
my_array.append(60)
print(f"Array after appending 60: {my_array}")

# 4. Insert an item at a specific position


# Insert 25 at index 2 (third position)
my_array.insert(2, 25)
print(f"Array after inserting 25 at index 2: {my_array}")

# 5. Reverse the order of the items


my_array.reverse()
print(f"Array after reversing: {my_array}")

# Call the function to perform array operations


array_operations()
SAMPLE OUTPUT

Original Array: [10, 20, 30, 40, 50]


Displaying Array: [10, 20, 30, 40, 50]
Array after appending 60: [10, 20, 30, 40, 50, 60]
Array after inserting 25 at index 2: [10, 20, 25, 30, 40, 50, 60]
Array after reversing: [60, 50, 40, 30, 25, 20, 10]

ACTUAL OUTPUT:

DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25

RESULT:

IV.4.A Python program to add, transpose and multiply two matrices.


Aim:

II [Link] CST Python Programming Page 27


def add_matrices(mat1, mat2):

"""

Adds two matrices.

Args:

mat1: The first matrix (list of lists).

mat2: The second matrix (list of lists).

Returns:

A new matrix that is the sum of mat1 and mat2, or None if dimensions
don't match.

"""

if len(mat1) != len(mat2) or len(mat1[0]) != len(mat2[0]):

return None # Matrices must have the same dimensions

rows = len(mat1)

cols = len(mat1[0])

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

for i in range(rows):

for j in range(cols):

result[i][j] = mat1[i][j] + mat2[i][j]

return result

def transpose_matrix(mat):

"""

Transposes a matrix.

Args:

mat: The matrix to transpose (list of lists).

II [Link] CST Python Programming Page 28


Returns:

A new transposed matrix.

"""

rows = len(mat)

cols = len(mat[0])

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

for i in range(rows):

for j in range(cols):

result[j][i] = mat[i][j]

return result

def multiply_matrices(mat1, mat2):

"""

Multiplies two matrices.

Args:

mat1: The first matrix (list of lists).

mat2: The second matrix (list of lists).

Returns:

A new matrix that is the product of mat1 and mat2, or None if


dimensions don't match.

"""

if len(mat1[0]) != len(mat2):

return None # Columns of mat1 must equal rows of mat2

rows1 = len(mat1)

cols1 = len(mat1[0])

rows2 = len(mat2)

cols2 = len(mat2[0])

II [Link] CST Python Programming Page 29


result = [[0 for _ in range(cols2)] for _ in range(rows1)]

for i in range(rows1):

for j in range(cols2):

for k in range(cols1):

result[i][j] += mat1[i][k] * mat2[k][j]

return result

# Example Usage:

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

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

addition_result = add_matrices(matrix_a, matrix_b)

if addition_SAMPLE OUTPUT

print("Matrix Addition:")

for row in addition_SAMPLE OUTPUT

print(row)

else:

print("Matrix addition failed: Dimensions do not match.")

transpose_a = transpose_matrix(matrix_a)

print("\nMatrix A Transpose:")

for row in transpose_a:

print(row)

multiplication_result = multiply_matrices(matrix_a, matrix_b)

if multiplication_SAMPLE OUTPUT

print("\nMatrix Multiplication:")

II [Link] CST Python Programming Page 30


for row in multiplication_SAMPLE OUTPUT

print(row)

else:

print("Matrix multiplication failed: Dimensions do not match.")

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:

II [Link] CST Python Programming Page 31


[Link] 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.
Aim:
# Import the math module to access mathematical functions like pi

import math

# Define a base class called Shape to represent a generic shape with methods
for calculating area and perimeter

class Shape:

# Placeholder method for calculating area (to be implemented in derived


classes)

def calculate_area(self):

pass

# Placeholder method for calculating perimeter (to be implemented in


derived classes)

def calculate_perimeter(self):

pass

# Define a derived class called Circle, which inherits from the Shape class

class Circle(Shape):

# Initialize the Circle object with a given radius

def __init__(self, radius):

[Link] = radius

# Calculate and return the area of the circle using the formula: π * r^2

def calculate_area(self):

return [Link] * [Link]**2

# Calculate and return the perimeter of the circle using the formula: 2π
* r

def calculate_perimeter(self):

II [Link] CST Python Programming Page 32


return 2 * [Link] * [Link]

# Define a derived class called Rectangle, which inherits from the Shape
class

class Rectangle(Shape):

# Initialize the Rectangle object with given length and width

def __init__(self, length, width):

[Link] = length

[Link] = width

# Calculate and return the area of the rectangle using the formula:
length * width

def calculate_area(self):

return [Link] * [Link]

# Calculate and return the perimeter of the rectangle using the formula:
2 * (length + width)

def calculate_perimeter(self):

return 2 * ([Link] + [Link])

# 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

def __init__(self, base, height, side1, side2, side3):

[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

II [Link] CST Python Programming Page 33


def calculate_area(self):

return 0.5 * [Link] * [Link]

# Calculate and return the perimeter of the triangle by adding the


lengths of its three sides

def calculate_perimeter(self):

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

# 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()

# Print the results for the Circle

print("Radius of the circle:", r)

print("Circle Area:", circle_area)

print("Circle Perimeter:", circle_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()

# Print the results for the Rectangle

print("\nRectangle: Length =", l, " Width =", w)

print("Rectangle Area:", rectangle_area)

II [Link] CST Python Programming Page 34


print("Rectangle Perimeter:", rectangle_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 = Triangle(base, height, s1, s2, s3)

triangle_area = triangle.calculate_area()

triangle_perimeter = triangle.calculate_perimeter()

print("Triangle Area:", triangle_area)

print("Triangle Perimeter:", triangle_perimeter)


SAMPLE OUTPUT
Radius of the circle: 7
Circle Area: 153.93804002589985
Circle Perimeter: 43.982297150257104

Rectangle: Length = 5 Width = 7


Rectangle Area: 35
Rectangle Perimeter: 24

Triangle: Base = 5 Height = 4 side1 = 4 side2 = 3 side3 = 5


Triangle Area: 10.0
Triangle Perimeter: 12

ACTUAL OUTPUT:

DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25

II [Link] CST Python Programming Page 35


RESULT:
UNIT-V: Introduction to Data Science:
[Link] program to check whether a JSON string contains complex object or not.
Aim:
import json

def contains_nested_structure(data):

"""

Recursively checks if a Python object (derived from JSON) contains nested


dictionaries or lists.

"""

if isinstance(data, dict):

for value in [Link]():

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

return True

if contains_nested_structure(value): # Recursively check nested


values

return True

elif isinstance(data, list):

for item in data:

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

return True

if contains_nested_structure(item): # Recursively check nested


items

return True

return False

# Example usage:

json_string_with_nested = '{"name": "Alice", "details": {"age": 30, "city":


"New York"}}'

json_string_simple = '{"name": "Bob", "age": 25}'

json_string_with_array = '{"items": [1, 2, {"key": "value"}]}'

II [Link] CST Python Programming Page 36


parsed_nested = [Link](json_string_with_nested)

parsed_simple = [Link](json_string_simple)

parsed_array = [Link](json_string_with_array)

print(f"'{json_string_with_nested}' contains complex object:


{contains_nested_structure(parsed_nested)}")

print(f"'{json_string_simple}' contains complex object:


{contains_nested_structure(parsed_simple)}")
print(f"'{json_string_with_array}' contains complex object:
{contains_nested_structure(parsed_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:

II [Link] CST Python Programming Page 37


[Link] Program to demonstrate NumPy arrays creation using array () function.
import numpy as np
Aim:

# Create a 1-D NumPy array from a Python list

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

array_from_list = [Link](list_data)

print("1-D Array from List:")

print(array_from_list)

print("Type:", type(array_from_list))

print("-" * 30)

# Create a 1-D NumPy array from a Python tuple

tuple_data = (10, 20, 30, 40)

array_from_tuple = [Link](tuple_data)

print("1-D Array from Tuple:")

print(array_from_tuple)

print("Type:", type(array_from_tuple))

print("-" * 30)

# Create a 2-D NumPy array (matrix) from a nested Python list

nested_list_data = [[1, 2, 3], [4, 5, 6]]

array_2d_from_list = [Link](nested_list_data)

print("2-D Array from Nested List:")

print(array_2d_from_list)

print("Shape:", array_2d_from_list.shape)

print("Type:", type(array_2d_from_list))

print("-" * 30)

II [Link] CST Python Programming Page 38


# Create a 3-D NumPy array from a nested Python list

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

array_3d_from_list = [Link](nested_list_3d)

print("3-D Array from Nested List:")

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

II [Link] CST Python Programming Page 39


RESULT:

[Link] program to demonstrate use of ndim, shape, size, dtype.


Aim:
import numpy as np
# Create a 2D NumPy array
arr = [Link]([[1, 2, 3], [4, 5, 6]])

print(f"Original array:\n{arr}\n")

# ndim: Number of dimensions

num_dimensions = [Link]

print(f"Number of dimensions (ndim): {num_dimensions}")

II [Link] CST Python Programming Page 40


# shape: Tuple representing the size of the array in each dimension

array_shape = [Link]

print(f"Shape of the array (shape): {array_shape}")

# size: Total number of elements in the array

total_elements = [Link]

print(f"Total number of elements (size): {total_elements}")

# dtype: Data type of the elements in the array

data_type = [Link]

print(f"Data type of the elements (dtype): {data_type}")

# Example with a 1D array

arr_1d = [Link]([10, 20, 30, 40])

print(f"\n1D array:\n{arr_1d}\n")

print(f"Number of dimensions (ndim) for 1D array: {arr_1d.ndim}")

print(f"Shape of the 1D array (shape): {arr_1d.shape}")

print(f"Total number of elements (size) for 1D array: {arr_1d.size}")

print(f"Data type of the elements (dtype) for 1D array: {arr_1d.dtype}")

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]

Number of dimensions (ndim) for 1D array: 1


Shape of the 1D array (shape): (4,)
Total number of elements (size) for 1D array: 4
Data type of the elements (dtype) for 1D array: int64

ACTUAL OUTPUT:

II [Link] CST Python Programming Page 41


DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25

RESULT:

[Link] program to demonstrate basic slicing, integer and Boolean indexing.


import numpy as np
Aim:
# Create a sample NumPy array

arr = [Link]([10, 20, 30, 40, 50, 60, 70, 80, 90, 100])

print("Original Array:", arr)

# 1. Basic Slicing

print("\n--- Basic Slicing ---")

# Slice from index 2 to 6 (exclusive of 6)

slice1 = arr[2:6]

print("Slice from index 2 to 6 (exclusive):", slice1)

# Slice from the beginning to index 5 (exclusive of 5)

II [Link] CST Python Programming Page 42


slice2 = arr[:5]

print("Slice from beginning to index 5 (exclusive):", slice2)

# Slice from index 4 to the end

slice3 = arr[4:]

print("Slice from index 4 to the end:", slice3)

# Slice with a step of 2

slice4 = arr[1:9:2]

print("Slice with step of 2 (index 1 to 9, step 2):", slice4)

# 2. Integer Indexing

print("\n--- Integer Indexing ---")

# Access a single element by its index

element1 = arr[3]

print("Element at index 3:", element1)

# Access multiple elements using a list of indices (Fancy Indexing)

elements_multiple = arr[[0, 5, 8]]

print("Elements at indices 0, 5, and 8:", elements_multiple)

# 3. Boolean Indexing

print("\n--- Boolean Indexing ---")

# Create a boolean mask based on a condition

boolean_mask = arr > 50

print("Boolean mask (elements > 50):", boolean_mask)

# Apply the boolean mask to filter the array

filtered_arr = arr[boolean_mask]

print("Filtered array (elements > 50):", filtered_arr)

# Another example of boolean indexing

filtered_arr_even = arr[arr % 20 == 0]

print("Filtered array (elements divisible by 20):", filtered_arr_even)


SAMPLE OUTPUT

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

II [Link] CST Python Programming Page 43


--- Basic Slicing ---
Slice from index 2 to 6 (exclusive): [30 40 50 60]
Slice from beginning to index 5 (exclusive): [10 20 30 40 50]
Slice from index 4 to the end: [ 50 60 70 80 90 100]
Slice with step of 2 (index 1 to 9, step 2): [20 40 60 80]

--- Integer Indexing ---


Element at index 3: 40
Elements at indices 0, 5, and 8: [10 60 90]

--- Boolean Indexing ---


Boolean mask (elements > 50): [False False False False False True True True True
True]
Filtered array (elements > 50): [ 60 70 80 90 100]
Filtered array (elements divisible by 20): [ 20 40 60 80 100]
ACTUAL OUTPUT:

DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25

RESULT:

[Link] program to find min, max, sum, cumulative sum of array


Aim:
def analyze_array(arr):

"""

Analyzes an array to find its minimum, maximum, total sum, and cumulative
sum.

Args:

arr (list): The input array (list of numbers).

Returns:

tuple: A tuple containing:

- min_val (int/float): The minimum value in the array.

- max_val (int/float): The maximum value in the array.

II [Link] CST Python Programming Page 44


- total_sum (int/float): The sum of all elements in the array.

- cumulative_sum_list (list): A list containing the cumulative


sum.

"""

if not arr:

return None, None, 0, []

min_val = min(arr)

max_val = max(arr)

total_sum = sum(arr)

cumulative_sum_list = []

current_sum = 0

for num in arr:

current_sum += num

cumulative_sum_list.append(current_sum)

return min_val, max_val, total_sum, cumulative_sum_list

# Example usage:

my_array = [1, 5, 2, 8, 3]

min_val, max_val, total_sum, cumulative_sum = analyze_array(my_array)

print(f"Original Array: {my_array}")


print(f"Minimum Value: {min_val}")
print(f"Maximum Value: {max_val}")
print(f"Total Sum: {total_sum}")
print(f"Cumulative Sum: {cumulative_sum}")

my_empty_array = []
min_val_empty, max_val_empty, total_sum_empty, cumulative_sum_empty =
analyze_array(my_empty_array)

print(f"\nEmpty Array Analysis:")


print(f"Minimum Value: {min_val_empty}")
print(f"Maximum Value: {max_val_empty}")
print(f"Total Sum: {total_sum_empty}")
print(f"Cumulative Sum: {cumulative_sum_empty}")

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]

Empty Array Analysis:

II [Link] CST Python Programming Page 45


Minimum Value: None
Maximum Value: None
Total Sum: 0
Cumulative Sum: []
ACTUAL OUTPUT:

DEPARTMENT OF CST
PERFORMANCE 10
RECORD 10
VIVA-VOCE 5
TOTAL 25

RESULT:

II [Link] CST Python Programming Page 46

You might also like