0% found this document useful (0 votes)
7 views58 pages

23a05304 Python Programming Lab Manual

The document is a laboratory master manual for a Python Programming course at Sri Venkateswara College of Engineering and Technology. It outlines the vision and mission of the institution and the Electronics and Communication Engineering department, along with program educational objectives, specific outcomes, and course objectives. Additionally, it includes a list of experiments to be conducted, demonstrating various Python programming concepts and techniques.

Uploaded by

polokishoreff
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
7 views58 pages

23a05304 Python Programming Lab Manual

The document is a laboratory master manual for a Python Programming course at Sri Venkateswara College of Engineering and Technology. It outlines the vision and mission of the institution and the Electronics and Communication Engineering department, along with program educational objectives, specific outcomes, and course objectives. Additionally, it includes a list of experiments to be conducted, demonstrating various Python programming concepts and techniques.

Uploaded by

polokishoreff
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 58

23A05304- PYTHON PROGRAMMING

SRI VENKATESWARA COLLEGE OF ENGINEERING AND TECHNOLOGY


(AUTONOMOUS)

R. V. S NAGAR CHITTOOR-517 127

DEPARTMENT OF ELECTRONICS AND COMMUNICATION ENGINEERING

LABORATORY MASTER MANUAL

LAB CODE : 23A05304

LAB NAME : PYTHON PROGRAMMING

YEAR & SEMESTER : II B. TECH I SEM

REGULATIONS : R-23

Prepared by

Dr. Om Prakash
(Associate Professor)
23A05304- PYTHON PROGRAMMING

Vision and Mission of the institute

Vision

 To carve the youth as dynamic, competent, valued and knowledgeable


professionals who shall lead the Nation to a better future and to mould the institution
into a Center of Academic Excellence and Advanced Research.

Mission

 To Provide quality education, student-centered teaching-learning processes and


state-of-art infrastructure for professional aspirants hailing from both rural and
urban areas.
 To Impart technical education that encourages independent thinking, develops
strong domain of knowledge, contemporary skills and positive attitudes towards
holistic growth of young minds.
23A05304- PYTHON PROGRAMMING

Vision and Mission of the Electronics and Communications Department

VISION

To become a center of excellence in the field of Electronics and Communications


offering higher order of learning and conducting contemporary research thereby
producing globally competitive and ethically strong engineering professionals.

MISSION

 Establish a scintillating learning environment to produce quality graduates with


passion for knowledge and creativity in the field of Electronics and Communication
Engineering.
 Impart quality education through periodically updated curriculum to meet the
hallenges of the industry and research at the global level.
 Enhancing employability of the students by providing skills through comprehensive
experiential learning.
 Developing professional etiquette and ethical integrity among the students to face
real-time life challenges.
 Empower the faculty through continuous training in domain, research and
pedagogy for enhancing learning outcomes of the students and Research output.

Programme Educational Objectives (PEOs) :

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.

Programme Specific Outcomes (PSOs) :

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

Programme Outcomes (POs) :

Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,


PO1
and an engineering specialization to the solution of complex engineering problems.
Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
PO2 problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and Engineering sciences
Design/development of solutions: Design solutions for complex Engineering problems and design
PO3 system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge and research methods
PO4 including design of experiments, analysis and interpretation of data, and synthesis of the information
to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
PO5 engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
PO6 health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional
engineering practice.
Environment and sustainability: Understand the impact of the professional engineering solutions in
PO7 societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
Ethics: Apply ethical principles and commit to professional ethics and Responsibilities and norms of
PO8
the engineering practice.
Individual and team work: Function effectively as an individual, and as a member or leader in
PO9
diverse teams, and in multidisciplinary settings.

Communication: Communicate effectively on complex engineering Activities with the engineering


PO10 community and with society at large, such as, being able to comprehend and write effective reports
and design documentation, make effective presentations, and give and receive clear instructions.

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

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
4. Programming and to create practical and contemporary applications using
these
.
Outcomes:

Course Outcomes: After completion of the course, students will be able to


 Showcase adept command of Python syntax, deftly utilizing variables, data types,
control structures, functions, modules, and exception handling to engineer robust and
efficient code solutions. (L4)
 Apply Python programming concepts to solve a variety of computational problems (L3)
 Understand the principles of object-oriented programming (OOP) in Python, including
classes, objects, inheritance, polymorphism, and encapsulation, and apply them to
design and implement Python programs (L3)
 Proficient in using commonly used Python libraries and frameworks such as JSON, XML,
NumPy, pandas (L2)
 Exhibit competence in implementing and manipulating fundamental data structures
such as lists, tuples, sets, dictionaries (L3)

LIST OF EXPERIMENTS
Note: Minimum 25 Experiments to be conducted

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


2. Write a Program to display all prime numbers within an interval
3. Write a program to swap two numbers without using a temporary variable.
4. Demonstrate the following Operators in Python with suitable examples.
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
5. Write a program to add and multiply complex numbers
6. Write a program to print multiplication table of a given number.
7. Write a program to define a function with multiple return values.
8. Write a program to define a function using default arguments.
23A05304- PYTHON PROGRAMMING

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

I. Experiments beyond the Syllabus

SL. No LIST OF THE EXPERIMENT


23A05304- PYTHON PROGRAMMING

INDEX

Faculty
Sl. No Date NAME OF THE EXPERIMENT Pg. No.
Signature
23A05304- PYTHON PROGRAMMING
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

Write a program to find the largest element among three Numbers

Code:
# Function to find the largest of three numbers

def find_largest(a, b, c):

# Assume the first number is the largest

largest = a

# Check if the second number is greater than the largest so far

if b > largest:

largest = b

# Check if the third number is greater than the largest so far

if c > largest:

largest = c

return largest

# Input three numbers

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

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

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

# Call the function and print the result

largest_number = find_largest(num1, num2, num3)

print("The largest number is:", largest_number)

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

Write a Program to display all prime numbers within an interval

Code:
# Function to check if a number is prime

def is_prime(n):

if n <= 1:

return False

for i in range(2, int(n**0.5) + 1):

if n % i == 0:

return False

return True

# Function to find all prime numbers in a given interval

def find_primes_in_interval(start, end):

primes = []

for num in range(start, end + 1):

if is_prime(num):

primes.append(num)

return primes

# Input the interval

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

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

# Get the prime numbers in the interval

prime_numbers = find_primes_in_interval(start, end)

# Print the result

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

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

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

Code:

# Function to swap two numbers

def swap_numbers(a, b):

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

a=a+b

b=a-b

a=a-b

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

return a, b

# Input two numbers

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

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

# Call the function to swap the numbers and print the result

num1, num2 = swap_numbers(num1, num2)

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

Demonstrate the following Operators in Python with suitable examples.

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

print(f"Addition: {a} + {b} = {a + b}")

# Subtraction

print(f"Subtraction: {a} - {b} = {a - b}")

# Multiplication

print(f"Multiplication: {a} * {b} = {a * b}")

# Division

print(f"Division: {a} / {b} = {a / b}")

# Modulus

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

# Exponentiation

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

# Floor Division

print(f"Floor Division: {a} // {b} = {a // b}")

# Relational Operators

a = 10

b=5
23A05304- PYTHON PROGRAMMING

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

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

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

print(f"a != b: {a != b}")

print(f"a >= b: {a >= b}")

print(f"a <= b: {a <= b}")

# 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

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

a //= 3

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

# Logical Operators

a = True

b = False
23A05304- PYTHON PROGRAMMING

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

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

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

# Bitwise Operators

a = 10 # (1010 in binary)

b = 4 # (0100 in binary)

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

print(f"a | b: {a | b}") # OR

print(f"a ^ b: {a ^ b}") # XOR

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

print(f"a << 2: {a << 2}") # Left Shift

print(f"a >> 2: {a >> 2}") # Right Shift

# Ternary Operator

a = 10

b = 20

max_value = a if a > b else b

print(f"Maximum value between {a} and {b} is: {max_value}")

# Membership Operators

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

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

print(f"6 in list: {6 in list}")

print(f"6 not in list: {6 not in list}")


23A05304- PYTHON PROGRAMMING

# Identity Operators

a = 10

b = 10

c=a

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

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

list1 = [1, 2, 3]

list2 = [1, 2, 3]

list3 = list1

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

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

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

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

Write a program to add and multiply complex numbers

Code:
# Define a class for Complex numbers

class Complex:

def __init__(self, real, imag):

self.real = real

self.imag = imag

def __add__(self, other):

return Complex(self.real + other.real, self.imag + other.imag)

def __mul__(self, other):

real_part = self.real * other.real - self.imag * other.imag

imag_part = self.real * other.imag + self.imag * other.real

return Complex(real_part, imag_part)

def __str__(self):

return f"{self.real} + {self.imag}i"

# Function to add and multiply complex numbers

def add_and_multiply_complex(c1, c2):

sum_complex = c1 + c2

product_complex = c1 * c2

return sum_complex, product_complex


23A05304- PYTHON PROGRAMMING

# Input two complex numbers

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

# Create complex number objects

c1 = Complex(real1, imag1)

c2 = Complex(real2, imag2)

# Call the function and print the results

sum_complex, product_complex = add_and_multiply_complex(c1, c2)

print(f"Sum of the complex numbers: {sum_complex}")

print(f"Product of the complex numbers: {product_complex}")

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

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


Code:

# Function to print the multiplication table of a given number

def print_multiplication_table(number, upto=10):

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

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

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

# Input the number

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

# Call the function to print the multiplication table

print_multiplication_table(number, upto)

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

Write a program to define a function with multiple return values.


Code:

# Function to perform arithmetic operations and return multiple values

def arithmetic_operations(a, b):

addition = a + b

subtraction = a - b

multiplication = a * b

division = a / b if b != 0 else 'undefined' # Avoid division by zero

return addition, subtraction, multiplication, division

# Input two numbers

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

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

# Call the function and store the return values

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

# Print the results

print(f"The results of arithmetic operations on {num1} and {num2} are:")

print(f"Addition: {add}")

print(f"Subtraction: {sub}")

print(f"Multiplication: {mul}")

print(f"Division: {div}")

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

Write a program to define a function using default arguments.

Code:
# Function to calculate the power of a number with a default exponent

def power(base, exponent=2):

return base ** exponent

# Call the function with both arguments

result1 = power(5, 3)

print(f"5 raised to the power of 3 is: {result1}")

# Call the function with only the base argument

result2 = power(5)

print(f"5 raised to the power of 2 (default exponent) is: {result2}")

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

input_string = input("Enter a string: ")

# Call the function to find the length of the string

length_of_string = string_length(input_string)

# Print the result

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

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

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


Code:

# Function to check if a substring is present in a given string

def is_substring_present(main_string, substring):

# Iterate through the main string

for i in range(len(main_string) - len(substring) + 1):

# Check if the substring matches the part of the main string

if main_string[i:i + len(substring)] == substring:

return True

return False

# Input the main string and the substring

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

substring = input("Enter the substring to search for: ")

# Call the function and store the result

result = is_substring_present(main_string, substring)

# Print the result

if result:

print(f"The substring '{substring}' is present in the main string.")

else:

print(f"The substring '{substring}' is not present in the main string.")

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

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


Code:

i. additionii. insertioniii. slicing

# Define a function to perform operations on a list

def list_operations():

# Initial list

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

# i. Addition: Add elements to the list

# Adding a single element

my_list.append(6)

# Adding multiple elements

my_list.extend([7, 8, 9])

print("List after addition:", my_list)

# ii. Insertion: Insert an element at a specific position

# Insert element '10' at index 2

my_list.insert(2, 10)

print("List after insertion:", my_list)

# iii. Slicing: Extract a portion of the list

# Extract elements from index 2 to 5 (exclusive)

sliced_list = my_list[2:5]

print("Sliced list from index 2 to 5:", sliced_list)

# Call the function to perform the operations

list_operations()
23A05304- PYTHON PROGRAMMING

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

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


Code:

# Define a function to demonstrate built-in list functions

def list_builtin_functions():

# Initial list

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

# 1. `len()`: Returns the number of elements in the list

length = len(my_list)

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

# 2. `max()`: Returns the maximum element in the list

maximum = max(my_list)

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

# 3. `min()`: Returns the minimum element in the list

minimum = min(my_list)

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

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

total_sum = sum(my_list)

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

# 5. `sorted()`: Returns a new list with elements sorted in ascending order

sorted_list = sorted(my_list)

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

# Call the function to demonstrate the built-in functions

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:

# Define tuples for two members

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

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

# Concatenate the tuples

combined_members = member1 + member2

# Print the concatenated tuple

print("Concatenated Tuple:", combined_members)

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

# Define a set of vowels

vowels = 'aeiouAEIOU'

# Create a function to check if a character is a vowel

is_vowel = lambda char: char in vowels

# Use map to apply the is_vowel function to each character in the string and filter out non-
vowels

vowel_count = sum(map(is_vowel, s))

return vowel_count

# Input a string

input_string = input("Enter a string: ")

# Call the function to count the number of vowels

vowel_count = count_vowels(input_string)

# Print the result

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

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

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


Code:

# Function to check if a key exists in a dictionary

def key_exists(dictionary, key):

# Use the `in` operator to check if the key exists in the dictionary

return key in dictionary

# Define a dictionary

sample_dict = {

'name': 'Alice',

'age': 25,

'city': 'New York'

# Input the key to check

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

# Call the function to check if the key exists

exists = key_exists(sample_dict, key_to_check)

# Print the result

if exists:

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:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

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


Code:

# Function to add a new key-value pair to a dictionary

def add_key_value(dictionary, key, value):

dictionary[key] = value

return dictionary

# Define an existing dictionary

sample_dict = {

'name': 'Alice',

'age': 25,

'city': 'New York'

# Input the new key and value to add

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

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

# Add the new key-value pair to the dictionary

updated_dict = add_key_value(sample_dict, new_key, new_value)

# Print the updated dictionary

print("Updated dictionary:", updated_dict)

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

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

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

# Define a dictionary with numerical values

sample_dict = {

'a': 10,

'b': 20,

'c': 30,

'd': 40

# Calculate the sum of all the values in the dictionary

total_sum = sum_dict_values(sample_dict)

# Print the result

print("The sum of all the values in the dictionary is:", total_sum)

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:

def sort_words_in_file(source_file, output_file):

# Read the content from the source file

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

# Read all words, convert to lowercase, and split into a list of words

words = file.read().lower().split()

# Sort the list of words

sorted_words = sorted(words)

# Write the sorted words to the output file, one word per line

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

for word in sorted_words:

file.write(word + '\n')

# Specify the source and output file names

source_file = 'source.txt'

output_file = 'sorted_output.txt'

# Call the function to process the files

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:

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

Code:
def print_lines_in_reverse(file_name):

try:

# Open the file for reading

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

# Read all lines in the file

lines = file.readlines()

# Print each line in reverse order

for line in lines:

# Strip the newline character and reverse the line

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

print(reversed_line)

except FileNotFoundError:

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

except PermissionError:

print(f"Error: You do not have permission to read '{file_name}'.")

except Exception as e:

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

# Specify the file name

file_name = 'sample.txt'

# Call the function to print lines in reverse order

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

# Open the file for reading

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

# Read all lines in the file

for line in file:

# Increment line count

num_lines += 1

# Increment character count (including spaces and newline)

num_characters += len(line)

# Increment word count

num_words += len(line.split())

# Print the statistics

print(f"Number of lines: {num_lines}")

print(f"Number of words: {num_words}")

print(f"Number of characters: {num_characters}")

except FileNotFoundError:
23A05304- PYTHON PROGRAMMING

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

except PermissionError:

print(f"Error: You do not have permission to read '{file_name}'.")

except Exception as e:

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

# Specify the file name

file_name = 'sample.txt'

# Call the function to compute file statistics

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

# Function to create an array

def create_array():

return array('i', [1, 2, 3, 4, 5])

# Function to display the array

def display_array(arr):

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

# Function to append an item to the array

def append_item(arr, item):

arr.append(item)

print(f"Item {item} appended to the array.")

# Function to insert an item at a specific position

def insert_item(arr, position, item):

arr.insert(position, item)

print(f"Item {item} inserted at position {position} in the array.")

# Function to reverse the order of items in the array

def reverse_array(arr):

arr.reverse()

print("Array order reversed.")


23A05304- PYTHON PROGRAMMING

# Main program

if __name__ == "__main__":

# Create an array

arr = create_array()

display_array(arr)

# Append an item to the array

append_item(arr, 6)

display_array(arr)

# Insert an item at position 2

insert_item(arr, 2, 9)

display_array(arr)

# Reverse the order of the array

reverse_array(arr)

display_array(arr)

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

Write a program to add, transpose and multiply two matrices

Code:

# Function to add two matrices

def add_matrices(matrix1, matrix2):

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

return result

# Function to transpose a matrix

def transpose_matrix(matrix):

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

return result

# Function to multiply two matrices

def multiply_matrices(matrix1, matrix2):

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


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

return result

# Function to display a matrix

def display_matrix(matrix):

for row in matrix:

print(row)

# Main program

if __name__ == "__main__":

# Define two matrices

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

added_matrix = add_matrices(matrix1, matrix2)

print("\nAdded Matrix:")

display_matrix(added_matrix)

# Transpose matrices

transposed_matrix1 = transpose_matrix(matrix1)

transposed_matrix2 = transpose_matrix(matrix2)

print("\nTransposed Matrix 1:")

display_matrix(transposed_matrix1)
23A05304- PYTHON PROGRAMMING

print("\nTransposed Matrix 2:")

display_matrix(transposed_matrix2)

# Multiply matrices

multiplied_matrix = multiply_matrices(matrix1, matrix2)

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

raise NotImplementedError("Subclass must implement abstract method")

def perimeter(self):

raise NotImplementedError("Subclass must implement abstract method")

# Circle subclass

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

# Triangle subclass

class Triangle(Shape):
23A05304- PYTHON PROGRAMMING

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

self.side1 = side1

self.side2 = side2

self.side3 = side3

def area(self):

# Using Heron's formula

s = (self.side1 + self.side2 + self.side3) / 2

return math.sqrt(s * (s - self.side1) * (s - self.side2) * (s - self.side3))

def perimeter(self):

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

# Square subclass

class Square(Shape):

def __init__(self, side):

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"Circle with radius {circle.radius}")

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

print(f"Perimeter: {circle.perimeter():.2f}\n")

# Triangle instance

triangle = Triangle(3, 4, 5)

print(f"Triangle with sides {triangle.side1}, {triangle.side2}, {triangle.side3}")

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

print(f"Perimeter: {triangle.perimeter()}\n")

# Square instance

square = Square(4)

print(f"Square with side {square.side}")

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)

# Function to check if an object is complex

def check_complex(obj):

if isinstance(obj, dict):

return any(isinstance(value, (dict, list)) for value in obj.values())

elif isinstance(obj, list):

return any(isinstance(item, (dict, list)) for item in obj)

return False

return check_complex(data)

except json.JSONDecodeError:

print("Invalid JSON string")

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_str3 = '[{"name": "John"}, {"name": "Doe"}]' # Simple JSON Array

json_str4 = '[{"name": "John", "address": {"city": "New York"}}, {"name": "Doe"}]' # Complex JSON
Array
23A05304- PYTHON PROGRAMMING

print("Is JSON 1 complex?", is_complex(json_str1))

print("Is JSON 2 complex?", is_complex(json_str2))

print("Is JSON 3 complex?", is_complex(json_str3))

print("Is JSON 4 complex?", is_complex(json_str4))

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

Python Program to demonstrate NumPy arrays creation using array ()


function.
Code:

import numpy as np

# One-dimensional array

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

print("One-dimensional array:")

print(one_d_array)

# Two-dimensional array

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

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)

# Array with specific data type

float_array = np.array([1, 2, 3, 4, 5], dtype=float)

print("\nArray with float data type:")

print(float_array)

# Array with complex numbers

complex_array = np.array([1 + 2j, 3 + 4j, 5 + 6j])


23A05304- PYTHON PROGRAMMING

print("\nArray with complex numbers:")

print(complex_array)

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

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

Code:

import numpy as np

# Create a one-dimensional array

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

print("One-dimensional array:")

print(one_d_array)

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

print(f"Shape: {one_d_array.shape}")

print(f"Size: {one_d_array.size}")

print(f"Data type: {one_d_array.dtype}")

print()

# Create a two-dimensional array

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

print("Two-dimensional array:")

print(two_d_array)

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

print(f"Shape: {two_d_array.shape}")

print(f"Size: {two_d_array.size}")

print(f"Data type: {two_d_array.dtype}")

print()

# Create a multi-dimensional array


23A05304- PYTHON PROGRAMMING

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

print("Multi-dimensional array:")

print(multi_d_array)

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

print(f"Shape: {multi_d_array.shape}")

print(f"Size: {multi_d_array.size}")

print(f"Data type: {multi_d_array.dtype}")

print()

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

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

Code:

import numpy as np

# Create a sample 2D array

array = np.array([

[10, 20, 30, 40],

[50, 60, 70, 80],

[90, 100, 110, 120]

])

print("Original Array:")

print(array)

print()

# Basic Slicing

# Extract a subarray from the original array

subarray = array[0:2, 1:3] # First two rows, and columns 2 and 3

print("Basic Slicing:")

print(subarray)

print()

# Integer Indexing

# Select specific elements

int_indexed_array = array[[0, 1, 2], [3, 0, 2]] # Elements (0,3), (1,0), (2,2)

print("Integer Indexing:")

print(int_indexed_array)
23A05304- PYTHON PROGRAMMING

print()

# Boolean Indexing

# Select elements based on a condition

bool_indexed_array = array[array > 50] # Elements greater than 50

print("Boolean Indexing:")

print(bool_indexed_array)

print()

OUTPUT:
23A05304- PYTHON PROGRAMMING

EXPERIMENT- DATE:

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

Code:

import numpy as np

# Create a sample array

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

print("Original Array:")

print(array)

print()

# Find the minimum value

min_value = np.min(array)

print("Minimum Value:", min_value)

# Find the maximum value

max_value = np.max(array)

print("Maximum Value:", max_value)

# Find the sum of all elements

sum_value = np.sum(array)

print("Sum of All Elements:", sum_value)

# Find the cumulative sum of all elements

cumulative_sum = np.cumsum(array)

print("Cumulative Sum of All Elements:")

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:

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

b) Perform various data selection operations on Data Frame

Code:

import pandas as pd

# Create a dictionary with five keys, each containing a list of at least 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]

# Convert the dictionary to a pandas DataFrame

df = pd.DataFrame(data_dict)

print("DataFrame:")

print(df)

print()

# a) Apply head() function to the DataFrame

print("Head of the DataFrame:")

print(df.head())

print()
23A05304- PYTHON PROGRAMMING

# b) Perform various data selection operations on DataFrame

# Select a single column

print("Column 'A':")

print(df['A'])

print()

# Select multiple columns

print("Columns 'A' and 'B':")

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

print()

# Select a row by index (e.g., the first row)

print("First Row:")

print(df.iloc[0])

print()

# Select multiple rows by index (e.g., first three rows)

print("First Three Rows:")

print(df.iloc[:3])

print()

# Select specific rows and columns (e.g., first two rows and 'A' and 'C' columns)

print("First Two Rows and Columns 'A' and 'C':")

print(df.loc[:1, ['A', 'C']])

print()
23A05304- PYTHON PROGRAMMING

# Select rows based on a condition (e.g., where values in column 'B' are greater than 15)

print("Rows where column 'B' values are greater than 15:")

print(df[df['B'] > 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

import matplotlib.pyplot as plt

# Create a dictionary with five keys, each containing a list of at least 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]

# Convert the dictionary to a pandas DataFrame

df = pd.DataFrame(data_dict)

# Select two columns for visualization

col1 = 'A'

col2 = 'B'

# Scatter plot

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

plt.subplot(1, 2, 1)

plt.scatter(df[col1], df[col2], color='blue', marker='o')

plt.title(f'Scatter Plot of {col1} vs {col2}')


23A05304- PYTHON PROGRAMMING

plt.xlabel(col1)

plt.ylabel(col2)

plt.grid(True)

# Line plot

plt.subplot(1, 2, 2)

plt.plot(df[col1], df[col2], color='red', marker='o')

plt.title(f'Line Plot of {col1} vs {col2}')

plt.xlabel(col1)

plt.ylabel(col2)

plt.grid(True)

plt.tight_layout()

plt.show()

OUTPUT:

You might also like