23a05304 Python Programming Lab Manual
23a05304 Python Programming Lab Manual
REGULATIONS : R-23
Prepared by
Dr. Om Prakash
(Associate Professor)
23A05304- PYTHON PROGRAMMING
Vision
Mission
VISION
MISSION
Utilize knowledge, skills, and resources to enrich professional careers to pursue higher
PEO1
studies in the electronics and communication engineering and allied areas.
PEO2 Develop entrepreneurship skills to achieve professional success with start-ups.
Develop attitude in lifelong learning and practice the profession with Integrity and
PEO3
responsibility.
Design and develop dedicated engineering circuits and systems using the concepts,
PSO1 principles and methodologies in electronics, communication and signal processing
applications in relevance to industry and society.
Use modern tools, techniques and methodologies to design, analyse and develop intelligent
PSO2 systems in VLSI, Embedded and modern Semiconductor technology for customized
solutions.
Appropriate principles and algorithms to implement secured communication systems for
PSO3 problem solving Using signals, images, information from radars and satellite, fiber optics,
wired and wireless systems.
23A05304- PYTHON PROGRAMMING
Project management and Finance: Demonstrate knowledge and Understanding of the engineering
PO11 and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multi disciplinary environments.
Life-long learning: Recognize the need for, and have the preparation and ability to engage in
PO12
independent and life-long learning in the broadest Context of technological change.
23A05304- PYTHON PROGRAMMING
Objectives:
Enable the students
LIST OF EXPERIMENTS
Note: Minimum 25 Experiments to be conducted
9. Write a program to find the length of the string without using any library functions.
10. Write a program to check if the substring is present in a given string or not.
11. Write a program to perform the given operations on a list:
i. additionii. insertioniii. slicing
12. Write a program to perform any 5 built-in functions by taking any list.
13. Write a program to create tuples (name, age, address, college) for at least two members and
concatenate the tuples and print the concatenated tuples.
14. Write a program to count the number of vowels in a string (No control flow allowed).
15. Write a program to check if a given key exists in a dictionary or not.
16. Write a program to add a new key-value pair to an existing dictionary.
17. Write a program to sum all the items in a given dictionary.
18. 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.
19. Python program to print each line of a file in reverse order.
20. Python program to compute the number of characters, words and lines in a file.
21. Write a program to create, display, append, insert and reverse the order of the items in the
array.
22. Write a program to add, transpose and multiply two matrices.
23. 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.
24. Python program to check whether a JSON string contains complex object or not.
25. Python Program to demonstrate NumPy arrays creation using array () function.
26. Python program to demonstrate use of ndim, shape, size, dtype.
27. Python program to demonstrate basic slicing, integer and Boolean indexing.
28. Python program to find min, max, sum, cumulative sum of array
29. 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
23A05304- PYTHON PROGRAMMING
30. 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
INDEX
Faculty
Sl. No Date NAME OF THE EXPERIMENT Pg. No.
Signature
23A05304- PYTHON PROGRAMMING
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Code:
# Function to find the largest of three numbers
largest = a
if b > largest:
largest = b
if c > largest:
largest = c
return largest
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Code:
# Function to check if a number is prime
def is_prime(n):
if n <= 1:
return False
if n % i == 0:
return False
return True
primes = []
if is_prime(num):
primes.append(num)
return primes
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Code:
a=a+b
b=a-b
a=a-b
return a, b
# Call the function to swap the numbers and print the result
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
i) Arithmetic Operators ii) Relational Operators iii) Assignment Operators iv) Logical
Operators v) Bit wise Operators vi) Ternary Operator vii) Membership Operators viii)
Identity Operators
Code:
# Arithmetic Operators
a = 10
b=5
# Addition
# Subtraction
# Multiplication
# Division
# Modulus
# Exponentiation
# Floor Division
# Relational Operators
a = 10
b=5
23A05304- PYTHON PROGRAMMING
print(f"a == b: {a == b}")
print(f"a != b: {a != b}")
# Assignment Operators
a = 10
print(f"Initial 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 %= 3
print(f"a %= 3: {a}")
a **= 2
a //= 3
# Logical Operators
a = True
b = False
23A05304- PYTHON PROGRAMMING
print(f"a or b: {a or b}")
# Bitwise Operators
a = 10 # (1010 in binary)
b = 4 # (0100 in binary)
print(f"a | b: {a | b}") # OR
# Ternary Operator
a = 10
b = 20
# Membership Operators
list = [1, 2, 3, 4, 5]
# Identity Operators
a = 10
b = 10
c=a
print(f"a is b: {a is b}")
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Code:
# Define a class for Complex numbers
class Complex:
self.real = real
self.imag = imag
def __str__(self):
sum_complex = c1 + c2
product_complex = c1 * c2
real1 = float(input("Enter the real part of the first complex number: "))
imag1 = float(input("Enter the imaginary part of the first complex number: "))
real2 = float(input("Enter the real part of the second complex number: "))
imag2 = float(input("Enter the imaginary part of the second complex number: "))
c1 = Complex(real1, imag1)
c2 = Complex(real2, imag2)
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
number = int(input("Enter the number for which you want the multiplication table: "))
upto = int(input("Enter the range up to which you want the multiplication table (default is 10): "))
print_multiplication_table(number, upto)
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
addition = a + b
subtraction = a - b
multiplication = a * b
print(f"Addition: {add}")
print(f"Subtraction: {sub}")
print(f"Multiplication: {mul}")
print(f"Division: {div}")
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Code:
# Function to calculate the power of a number with a default exponent
result1 = power(5, 3)
result2 = power(5)
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Write a program to find the length of the string without using any library functions.
Code:
# Function to find the length of a string without using any library functions
def string_length(s):
length = 0
for char in s:
length += 1
return length
# Input a string
length_of_string = string_length(input_string)
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
return True
return False
if result:
else:
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
def list_operations():
# Initial list
my_list = [1, 2, 3, 4, 5]
my_list.append(6)
my_list.extend([7, 8, 9])
my_list.insert(2, 10)
sliced_list = my_list[2:5]
list_operations()
23A05304- PYTHON PROGRAMMING
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
def list_builtin_functions():
# Initial list
my_list = [4, 2, 9, 1, 5, 6, 7, 8, 3]
length = len(my_list)
maximum = max(my_list)
minimum = min(my_list)
total_sum = sum(my_list)
sorted_list = sorted(my_list)
list_builtin_functions()
23A05304- PYTHON PROGRAMMING
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Write a program to create tuples (name, age, address, college) for at least
two members and concatenate the tuples and print the concatenated tuples.
Code:
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Write a program to count the number of vowels in a string (No control flow
allowed).
Code:
# Function to count the number of vowels in a string without using control flow
def count_vowels(s):
vowels = 'aeiouAEIOU'
# Use map to apply the is_vowel function to each character in the string and filter out non-
vowels
return vowel_count
# Input a string
vowel_count = count_vowels(input_string)
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
# Use the `in` operator to check if the key exists in the dictionary
# Define a dictionary
sample_dict = {
'name': 'Alice',
'age': 25,
if exists:
else:
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
dictionary[key] = value
return dictionary
sample_dict = {
'name': 'Alice',
'age': 25,
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Code:
# Function to sum all the values in a dictionary
def sum_dict_values(dictionary):
# Use the `sum` function with the `values` method to sum all the values
return sum(dictionary.values())
sample_dict = {
'a': 10,
'b': 20,
'c': 30,
'd': 40
total_sum = sum_dict_values(sample_dict)
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
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.
Code:
# Read all words, convert to lowercase, and split into a list of words
words = file.read().lower().split()
sorted_words = sorted(words)
# Write the sorted words to the output file, one word per line
file.write(word + '\n')
source_file = 'source.txt'
output_file = 'sorted_output.txt'
sort_words_in_file(source_file, output_file)
print(f"Words from '{source_file}' have been sorted and written to '{output_file}'.")# Call the
function to process the files
sort_words_in_file(source_file, output_file)
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Code:
def print_lines_in_reverse(file_name):
try:
lines = file.readlines()
reversed_line = line.rstrip()[::-1]
print(reversed_line)
except FileNotFoundError:
except PermissionError:
except Exception as e:
file_name = 'sample.txt'
print_lines_in_reverse(file_name)
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Python program to compute the number of characters, words and lines in a file.
Code:
def compute_file_statistics(file_name):
try:
# Initialize counters
num_characters = 0
num_words = 0
num_lines = 0
num_lines += 1
num_characters += len(line)
num_words += len(line.split())
except FileNotFoundError:
23A05304- PYTHON PROGRAMMING
except PermissionError:
except Exception as e:
file_name = 'sample.txt'
compute_file_statistics(file_name)
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Write a program to create, display, append, insert and reverse the order of
the items in the array.
Code:
from array import array
def create_array():
def display_array(arr):
arr.append(item)
arr.insert(position, item)
def reverse_array(arr):
arr.reverse()
# Main program
if __name__ == "__main__":
# Create an array
arr = create_array()
display_array(arr)
append_item(arr, 6)
display_array(arr)
insert_item(arr, 2, 9)
display_array(arr)
reverse_array(arr)
display_array(arr)
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Code:
return result
def transpose_matrix(matrix):
return result
return result
def display_matrix(matrix):
print(row)
# Main program
if __name__ == "__main__":
matrix1 = [
23A05304- PYTHON PROGRAMMING
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
matrix2 = [
[9, 8, 7],
[6, 5, 4],
[3, 2, 1]
print("Matrix 1:")
display_matrix(matrix1)
print("\nMatrix 2:")
display_matrix(matrix2)
# Add matrices
print("\nAdded Matrix:")
display_matrix(added_matrix)
# Transpose matrices
transposed_matrix1 = transpose_matrix(matrix1)
transposed_matrix2 = transpose_matrix(matrix2)
display_matrix(transposed_matrix1)
23A05304- PYTHON PROGRAMMING
display_matrix(transposed_matrix2)
# Multiply matrices
print("\nMultiplied Matrix:")
display_matrix(multiplied_matrix)
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
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.
Code:
import math
# Base class
class Shape:
def area(self):
def perimeter(self):
# Circle subclass
class Circle(Shape):
self.radius = radius
def area(self):
def perimeter(self):
# Triangle subclass
class Triangle(Shape):
23A05304- PYTHON PROGRAMMING
self.side1 = side1
self.side2 = side2
self.side3 = side3
def area(self):
def perimeter(self):
# Square subclass
class Square(Shape):
self.side = side
def area(self):
return self.side ** 2
def perimeter(self):
return 4 * self.side
# Main program
if __name__ == "__main__":
# Circle instance
23A05304- PYTHON PROGRAMMING
circle = Circle(5)
print(f"Area: {circle.area():.2f}")
print(f"Perimeter: {circle.perimeter():.2f}\n")
# Triangle instance
triangle = Triangle(3, 4, 5)
print(f"Area: {triangle.area():.2f}")
print(f"Perimeter: {triangle.perimeter()}\n")
# Square instance
square = Square(4)
print(f"Area: {square.area()}")
print(f"Perimeter: {square.perimeter()}")
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Python program to check whether a JSON string contains complex object or not.
Code:
import json
def is_complex(json_str):
try:
data = json.loads(json_str)
def check_complex(obj):
if isinstance(obj, dict):
return False
return check_complex(data)
except json.JSONDecodeError:
return False
# Test cases
json_str1 = '{"name": "John", "age": 30, "city": "New York"}' # Simple JSON
json_str2 = '{"name": "John", "address": {"city": "New York", "zipcode": "10001"}}' # Complex JSON
json_str4 = '[{"name": "John", "address": {"city": "New York"}}, {"name": "Doe"}]' # Complex JSON
Array
23A05304- PYTHON PROGRAMMING
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
import numpy as np
# One-dimensional array
print("One-dimensional array:")
print(one_d_array)
# Two-dimensional array
print("\nTwo-dimensional array:")
print(two_d_array)
# Multi-dimensional array
multi_d_array = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])
print("\nMulti-dimensional array:")
print(multi_d_array)
print(float_array)
print(complex_array)
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Code:
import numpy as np
print("One-dimensional array:")
print(one_d_array)
print(f"Shape: {one_d_array.shape}")
print(f"Size: {one_d_array.size}")
print()
print("Two-dimensional array:")
print(two_d_array)
print(f"Shape: {two_d_array.shape}")
print(f"Size: {two_d_array.size}")
print()
print("Multi-dimensional array:")
print(multi_d_array)
print(f"Shape: {multi_d_array.shape}")
print(f"Size: {multi_d_array.size}")
print()
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Code:
import numpy as np
array = np.array([
])
print("Original Array:")
print(array)
print()
# Basic Slicing
print("Basic Slicing:")
print(subarray)
print()
# Integer Indexing
print("Integer Indexing:")
print(int_indexed_array)
23A05304- PYTHON PROGRAMMING
print()
# Boolean Indexing
print("Boolean Indexing:")
print(bool_indexed_array)
print()
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
Code:
import numpy as np
print("Original Array:")
print(array)
print()
min_value = np.min(array)
max_value = np.max(array)
sum_value = np.sum(array)
cumulative_sum = np.cumsum(array)
print(cumulative_sum)
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
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:
Code:
import pandas as pd
# Create a dictionary with five keys, each containing a list of at least ten values
data_dict = {
'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]
df = pd.DataFrame(data_dict)
print("DataFrame:")
print(df)
print()
print(df.head())
print()
23A05304- PYTHON PROGRAMMING
print("Column 'A':")
print(df['A'])
print()
print(df[['A', 'B']])
print()
print("First Row:")
print(df.iloc[0])
print()
print(df.iloc[:3])
print()
# Select specific rows and columns (e.g., first two rows and 'A' and 'C' columns)
print()
23A05304- PYTHON PROGRAMMING
# Select rows based on a condition (e.g., where values in column 'B' are greater than 15)
print()
OUTPUT:
23A05304- PYTHON PROGRAMMING
EXPERIMENT- DATE:
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
Code:
import pandas as pd
# Create a dictionary with five keys, each containing a list of at least ten values
data_dict = {
'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]
df = pd.DataFrame(data_dict)
col1 = 'A'
col2 = 'B'
# Scatter plot
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.xlabel(col1)
plt.ylabel(col2)
plt.grid(True)
# Line plot
plt.subplot(1, 2, 2)
plt.xlabel(col1)
plt.ylabel(col2)
plt.grid(True)
plt.tight_layout()
plt.show()
OUTPUT: