'NEC' Python Programming Lab 2024 AIML
'NEC' Python Programming Lab 2024 AIML
Record
DEPARTMENT
OF
CSE (ARTIFICIAL INTELLIGENCE &
MACHINE LEARNING), ARTIFICIAL
INTELLIGENCE & MACHINE LEARNING
1
INSTITUTE’S VISION, MISSION & VALUES
Vision:
To emerge as a Centre of excellence in technical education with a blend of effective student
centric teaching learning practices as well as research for the transformation of lives and
community.
Mission:
M1: Provide the best class infra-structure to explore the field of engineering and research.
M2: Build a passionate and a determined team of faculty with student centric teaching, imbibing
experiential, innovative skills.
M3: Imbibe lifelong learning skills, entrepreneurial skills and ethical values in students for
addressing societal problems.
Values:
Student-centric education: Meeting the community’s and student’s needs by developing a
world-class educational environment with cultural values.
Excellence: Giving special attention towards the standards of integrity and performance to
help the institute in leading academic achievements and professional goals.
Collaboration: Seeking the latest input and working closely with all the industrial sectors and
Society for the continuous up gradation of the quality of education.
Diversity: Creating a favourable on-campus environment in which the goals and learning
styles of all students are recognised and nurtured.
Continuous Development: Encouraging enthusiastic, innovative thinkers and learners to
strive for personal growth in the world of inventions and start-ups.
Technological Advancement: Keeping pace with evolving technology and professional
trends to prepare all its students to achieve success in the workplace.
DEPARTMENT OF CSE (AIML)
Vision:
To empower students to become AI and ML professionals, driving industry innovation and
positively impacting society through cutting-edge technologies.
Mission:
M1: To establish a solid foundation in Artificial Intelligence and Machine Learning and
effectively address real-world challenges.
M2: To develop resilient professionals by encouraging them to create applications for industry
innovation.
M3: To cultivate a research-oriented mind set in students, encouraging them to create
applications that have practical value and make a positive impact on society.
PEO1: Graduates possess a strong knowledge of Artificial Intelligence and Machine Learning
principles, enabling them to effectively address real-world challenges.
PEO2: Graduates continuously enhance their skills and adapt to the evolving field of AI and ML,
empowering them to confidently face future challenges.
PEO3: Graduates apply their AI and ML knowledge to develop practical applications that
positively impact society and address societal challenges.
PSO1: Apply a range of AI and ML techniques to analyse and solve real-world problems
effectively.
PSO2: Design and develop AI systems by integrating appropriate algorithms, models, and
technologies to address specific problem domains.
PSO3: Develop the ethical implications and societal impact of AI and ML technologies.
PROGRAM OUTCOMES (POs)
PO1: Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
PO2: Problem analysis: Identify, formulate, review research literature, and analyse complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences, and
engineering sciences.
PO3: Design / development of solutions: Design solutions for complex engineering problems and design
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.
PO4: Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5: Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities with an
understanding of the limitations.
PO6: The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7: Environment and sustainability: Understand the impact of the professional engineering solutions
in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8: Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of
the engineering practice.
PO9: Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities with the engineering
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.
PO11: Project management and finance: Demonstrate knowledge and understanding of the engineering
and management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
P012: Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
COURSE OBJECTIVES:
The main objectives of the course are to
Introduce core programming concept of Python programming language.
Demonstrate about Python data structures like Lists, Tuples, Sets and dictionaries.
Implements Functions, Modules and Regular Expressions in Python Programming and to crate
practical and contemporary applications using these
COURSE OUTCOMES:
At the end of the course students will be able to
CO 1: Make use of control flow statements and functions to develop python programs. [K3].
CO 2: Develop Python programs using strings, Lists, dictionaries, tuples and sets. [K3].
CO 3: Develop Python programs on object oriented programming and regular expressions. [K3].
CO 4: Develop Python programs using NumPy and Pandas. [K3].
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12
CO1 3 2 1 2 - - - - - - - -
CO2 3 2 - 2 - - - - - - - -
CO3 2 2 - 2 - - - - - - - -
CO4 2 2 1 2 - - - - - - - -
INDEX
Week PAGE
NAME OF THE EXPERIMENT
No. No.
1. Write a program to create tuples (name, age, address, college) for at least two
members and concatenate the tuples and print the concatenated tuples.
5.
2. Write a program to count the number of vowels in a string (No control flow
allowed).
3. Write a program to check if a given key exists in a dictionary or not.
6.
4. Write a program to add a new key-value pair to an existing dictionary.
5. Write a program to sum all the items in a given dictionary.
1. Write a program to sort words in a file and put them in another file. The output file
should have only lower-case words, so any upper-case words from source must be
7.
lowered.
2. Python program to print each line of a file in reverse order.
3. Python program to compute the number of characters, words and lines in a file.
8. 4. Write a program to create, display, append, insert and reverse the order of the items
in the array.
5. Write a program to add, transpose and multiply two matrices.
6. Write a Python program to create a class that represents a shape. Include methods
9.
to calculate its area and perimeter. Implement subclasses for different shapes like
circle, triangle, and square.
1. Python program to check whether a JSON string contains complex object or not.
10. 2. Python Program to demonstrate NumPy arrays creation using array () function.
3. Python program to demonstrate use of ndim, shape, size, dtype.
REFERENCE BOOKS:
1. Gowrishankar S, Veena A., Introduction to Python Programming, CRC Press
2. 2. Python Programming, S Sridhar, J Indumathi, V M Hariharan, 2 ndEdition, Pearson, 2024
3. Introduction to Programming Using Python, Y. Daniel Liang, Pearson
ONLINE LEARNING RESOURCES / VIRTUAL LABS:
1. https://www.coursera.org/learn/python-for-applied-data-science-ai
2. https://www.coursera.org/learn/python?specialization=python#syllabus
Experiment-1
Date:
PROGRAM-1
AIM
The aim of this program is to find the largest element among three given numbers.
ALGORITHM
Step-2: Compare the first number with the second and third numbers.
Step-3: If the first number is greater than or equal to both the second and third numbers, it is
the largest.
Step-4: If not, compare the second and third numbers to determine the largest among them.
PROGRAM
largest = num1
largest = num2
else:
largest = num3
Ans.
Ans. ___________________________________________________________________________
3. Can you write the logic for finding the largest number using Python’s built-in functions?
Ans. ___________________________________________________________________________
4. How would you modify the program to find the largest number among more than three
numbers?
Ans.
5. What are the different ways to take input from the user in python?
Ans.
Python Programming
Experiment-2
Date:
PROGRAM-2
AIM
ALGORITHM
Step-1: Read the lower and upper bounds of the interval from the user.
Step-4: To check if a number is prime, iterate from 2 to the square root of the number.
Step-5: If the number is divisible by any number within this range, it is not prime. Otherwise,
it is prime.
PROGRAM
import math
6
for num in range(lower, upper + 1):
if num > 1:
is_prime = True
if num % i == 0:
is_prime = False
break
if is_prime:
OUTPUT
VIVA QUESTIONS
Ans.
Ans. ___________________________________________________________________________
Ans. ___________________________________________________________________________
Ans.
5. How do you handle the edge cases in your program (e.g., intervals with negative num
Ans.
Lab
Record
Experiment-3
Date:
PROGRAM-3
AIM
The Aim of this Program to swap two numbers without using a temporary variable.
ALGORITHM
Step-3: Swap the values of num1 and num2 without using a temporary variable.
PROGRAM
11
OUTPUT
VIVA QUESTIONS
Ans.
Ans.
Ans.
Ans.
Ans.
Python Programming
Experiment-4
Date:
PROGRAM-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
i) Arithmetic Operators
AIM
The aim is to perform basic arithmetic operations such as addition, subtraction, multiplication,
division, etc., on two numbers.
ALGORITHM
PROGRAM
# Reading input
16
addition = num1 + num2
# Printing output
print("Addition:", addition)
print("Subtraction:", subtraction)
print("Multiplication:", multiplication)
print("Division:", division)
print("Modulus:", modulus)
print("Exponentiation:", exponentiation)
OUTPUT
ii) Relational Operators
AIM
The aim is to compare two values and determine the relationship between them.
ALGORITHM
PROGRAM
# Reading input
AIM
ALGORITHM
PROGRAM
x=5
x += 3 # Equivalent to x = x + 3
y = 10
y -= 2 # Equivalent to y = y - 2
z=4
z *= 5 # Equivalent to z = z * 5
w = 16
w /= 4 # Equivalent to w = w / 4
a = 17
a %= 5 # Equivalent to a = a % 5
b=2
b **= 3 # Equivalent to b = b ** 3
c = 17
c //= 5 # Equivalent to c = c // 5
OUTPUT
AIM
ALGORITHM
PROGRAM
# Logical Operators
a = True
b = False
# AND operator
and_result = a and b
# OR operator
or_result = a or b
# NOT operator
not_result = not a
print(f"a or b: {or_result}")
print(f"not a: {not_result}")
OUTPUT
a and b: False
a or b: True
not a: False
V) BitwiseOperators
AIM
ALGORITHM
PROGRAM
# Bitwise Operators
a = 10 # 1010 in binary
b = 4 # 0100 in binary
# AND operator
and_result = a & b
# OR operator
or_result = a | b
# XOR operator
xor_result = a ^ b
# NOT operator
not_result = ~a
left_shift_result = a << 1
right_shift_result = a >> 1
print(f"a | b: {or_result}")
print(f"a ^ b: {xor_result}")
print(f"~a: {not_result}")
Output:
a & b: 0
a | b: 14
a ^ b: 14
~a: -11
a << 1: 20
a >> 1: 5
vi)Ternary
Operator AIM
ALGORITHM
Step-2: Use the ternary operator to assign a value based on the condition.
PROGRAM
# Ternary Operator
a = 10
b = 20
# Ternary operation
print(result)
Output:
b is greater
vii)Membership Operators
AIM
ALGORITHM
PROGRAM
numbers = [1, 2, 3, 4, 5]
is_in_list = 3 in numbers
Output:
AIM
ALGORITHM
Step-2: Use identity operators to check if they refer to the same object.
PROGRAM
# Define variables
a = [1, 2, 3]
b=a
c = [1, 2, 3]
result_is = a is b
result_is_not = a is not c
# Print results
Output:
a is b: True
a is not c: True
VIVA QUESTION
Ans.
Ans.
Ans.
Ans.
5. How do membership operators work and when would you use them?
Ans.
Python Programming
Experiment-5
Date:
PROGRAM-5
AIM
The aim of this program is to perform addition and multiplication of two complex numbers
using control flow statements in Python.
ALGORITHM
numbers.
Step-4: Convert the input strings into complex number objects.
Step-5: Use the defined functions to add and multiply the complex numbers.
PROGRAM
def main():
c1 = complex(input("Enter the first complex number (in the form a+bj): "))
c2 = complex(input("Enter the second complex number (in the form a+bj): "))
if __name__ == "__main__":
main()
OUTPUT
VIVA QUESTIONS
Ans.
Ans.
Ans.
Ans.
Ans.
Lab
Record
Experiment-6
Date:
PROGRAM-6
AIM
The aim of this program is to generate and print the multiplication table of a given number up
to a specified range.
ALGORITHM
Step-1: Prompt the user to input a number for which the multiplication table will be generated.
Step-2: Prompt the user to input the range up to which the table should be printed.
Step-4: For each iteration, multiply the given number by the current loop index.
PROGRAM
def main():
# Input the number for which the multiplication table will be generated
number = int(input("Enter the number for which you want the multiplication table: "))
table_range = int(input("Enter the range up to which the table should be printed: "))
39
result = number * i
if __name__ == "__main__":
main()
OUTPUT
VIVA QUESTIONS
Ans.
2. Can you modify the program to print the multiplication table for a range of numbers?
Ans.
Ans.
4. How can you take user input for the number and the range for the multiplication table?
Ans.
Ans.
Python Programming
Experiment-7
Date:
PROGRAM-7
AIM
To write a Python program that defines a function which returns multiple values.
ALGORITHM
Create a function that performs some operations and returns multiple values.
Perform operations
44
PROGRAM
sum_val = a + b
diff_val = a - b
prod_val = a * b
num1 = 10
num2 = 5
print(f"Sum: {sum_result}")
print(f"Difference: {diff_result}")
print(f"Product: {prod_result}")
OUTPUT
Sum: 15
Difference: 5
Product: 50
VIVA QUESTIONS
Ans.
2. What is tuple unpacking, and how is it used with functions returning multiple values?
Ans.
3. Can you provide an example where returning multiple values from a function is useful?
Ans.
Ans.
Ans.
Python Programming
Experiment-8
Date:
PROGRAM-8
AIM
ALGORITHM
Specify default values for some or all parameters in the function definition.
Step-3: Call the function
Call the function with and without providing arguments to see the effect of default values.
Step-4: Display the results
return a + b
result1 = add_numbers(5, 3)
result2 = add_numbers(7)
print(f"Result when only one argument is provided (default value used): {result2}")
OUTPUT
When the above program is executed, the output will be:
sql
Copy code
Ans.
Ans.
3. What happens if you call a function without providing some or all arguments when
default values are defined?
Ans.
4. Can you provide an example where default arguments are particularly useful?
Ans.
Ans.
Lab
Record
Experiment-9
Date:
PROGRAM-9
Write a program to find the length of the string without using any library functions
AIM
The aim of this program is to find the length of a string in Python without using any built-in
library functions like len().
ALGORITHM
Step-3: Counting: Increment the counter for each character until the end of the string (when
there are no more characters left to iterate over).
Step-4: Output: Print or return the counter value, which represents the length of the string.
PROGRAM
def string_length(s):
length = 0
for _ in s:
length += 1
53
return length
def main():
length = string_length(input_string)
if __name__ == "__main__":
main()
OUTPUT
VIVA QUESTIONS
1. How can you determine the length of a string without using built-in functions like len()?
Ans.
2. Can you explain the logic used to count characters in a string manually?
Ans.
3. How would you handle different types of input, such as an empty string or non-string data?
Ans.
Ans.
5. Can you think of any edge cases that might affect the accuracy of your string length
calculation?
Ans.
Lab
Record
Experiment-10
Date:
PROGRAM-10
AIM
To write a Python program that uses string concepts to check if a given substring is resent in a
specified string
ALGORITHM
Step-1: Input: Read the main string and the substring from the user.
Step-2: Check Presence: Use the in operator to determine if the substring is part of the main
string.
Step-3: Output: Print a message indicating whether the substring is found in the main string.
PROGRAM
def main():
57
# Input: Main string and substring
if is_substring_present(main_string, substring):
else:
if __name__ == "__main__":
main()
OUTPUT
VIVA QUESTIONS
Ans.
Ans.
3. How would you handle case sensitivity when checking for substrings?
Ans.
4. Can you write a function that performs the same task without using built-in operators?
Ans.
5. How would you improve the efficiency of substring search in large texts?
Ans.
Lab
Record
Experiment-11
Date:
PROGRAM-11
AIM
ALGORITHM
Use the insert() method to insert an element at a specified index in the list.
Step-3: Slicing
Use slicing (:) to extract a portion of the list based on start and end indices.
PROGRAM
def main():
# Initialize a list
my_list = [1, 2, 3, 4, 5]
# i. Addition
# ii. Insertion
# iii. Slicing
if __name__ == "__main__":
main()
OUTPUT
Ans.
Ans.
Ans.
Ans.
Ans.
Python Programming
Experiment-12
Date:
PROGRAM-12
AIM
The aim of this task is to showcase the usage of five built-in functions that operate on lists in
Python.
ALGORITHM
Step-1: Initialization
1. What are some common built-in functions available for lists in Python?
Ans.
Ans.
3. How do you find the maximum and minimum values in a list using built-in functions?
Ans.
4. What is the purpose of the sorted() function, and how does it differ from the sort() method?
Ans.
5. How do you use the enumerate() function with lists, and what are its advantages?
Ans.
Lab
Record
Experiment-13
Date:
PROGRAM-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.
AIM
To write a Python program to create tuples containing details of members (name, age, address,
college), concatenate the tuples, and print the concatenated tuple.
ALGORITHM
Step-1: Define the tuples: Create tuples for at least two members with the details (name,
age, address, college).
Step-2: Concatenate the tuples: Use the + operator to concatenate the tuples.
Step-3: Print the concatenated tuple: Display the result of the concatenation.
PROGRAM
71
print("Concatenated Tuple:", concatenated_tuple)
OUTPUT
Concatenated Tuple: ('Alice', 22, '123 Main St, Springfield', 'Springfield University', 'Bob',
23, '456 Elm St, Shelbyville', 'Shelbyville College')
VIVA QUESTIONS
Ans.
Ans.
Ans.
Ans.
Ans.
Lab
Record
Lab Record
Experiment-14
Date:
PROGRAM-14
Write a program to count the number of vowels in a string (No control flow allowed).
AIM
To write a program that counts the number of vowels in a given string without using control
flow statements (like if, for, while).
ALGORITHM
Step-1: Define Input String: Define the input string containing the text to be analysed.
Step-2: Create Vowel Set: Create a set of vowels for easy lookup.
Step-3: Count Vowels Using Built-in Functions: Use Python’s built-in functions and
methods to count the number of vowels without explicit control flow.
PROGRAM
def count_vowels(s):
vowels = set('aeiouAEIOU')
# Example usage
vowel_count = count_vowels(input_string)
75
Lab Record
OUTPUT
VIVA QUESTIONS
Ans.
Ans.
Ans.
Ans.
5. What are the advantages of using functional programming concepts like map and sum?
Ans.
Lab
Record
Experiment-15
Date:
PROGRAM-15
AIM
ALGORITHM
Call the function with a dictionary and a key to test the implementation.
Step-6: Display the result
79
PROGRAM
3.3.
OUTPUT
VIVA QUESTIONS
Ans.
Ans.
Ans.
Ans.
5. How does Python handle operations like checking if a key exists efficiently in dictionaries?
Ans.
Python Programming
Experiment-16
Date:
PROGRAM-16
AIM
To write a Python program that adds a new key-value pair to an existing dictionary.
ALGORITHM
Inside the function, add the new key-value pair to the dictionary.
Step-4: Return the updated dictionary
Call the function with a dictionary, a new key, and a new value to test the implementation.
Step-6: Display the result
Print the updated dictionary to verify the new key-value pair has been added
PROGRAM
dictionary[key] = value
return dictionary
sample_dict = {
'name': 'Alice',
'age': 25,
OUTPUT
Updated Dictionary: {'name': 'Alice', 'age': 25, 'city': 'New York', 'country': 'USA'}
VIVA QUESTIONS
Ans.
2. What happens if the key already exists when adding a new key-value pair in a dictionary?
Ans.
3. Why did you use a function add_to_dict instead of adding the key-value pair directly?
Ans.
4. Is the order of items preserved when adding a new key-value pair to a dictionary?
Ans.
5. How can you update an existing key’s value in a dictionary without overwriting other
keys?
Ans.
Lab
Record
Experiment-17
Date:
PROGRAM-17
AIM
To write a Python program that sums all the values in a given dictionary.
ALGORITHM
Step-2: Initialize Sum: Initialize a variable to hold the sum of the values.
Step-3: Iterate and Sum: Loop through the dictionary values and add each value to the sum.
PROGRAM
def sum_dictionary_items(input_dict):
total_sum = sum(input_dict.values())
return total_sum
# Main function to define a dictionary and print the sum of its values
def main():
89
# Example dictionary
my_dict = {
'a': 10,
'b': 20,
'c': 30,
'd': 40
total = sum_dictionary_items(my_dict)
if __name__ == "__main__":
main()
OUTPUT
Lab Record
VIVA QUESTIONS
Ans.
Ans.
Ans.
Ans.
5. What is the time complexity of summing all values in a dictionary using sum?
Ans.
Lab
Record
Experiment-18
Date:
PROGRAM-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.
AIM
To create a program that reads words from a file, sorts them alphabetically, converts any
uppercase words to lowercase, and then writes the sorted lowercase words into another file.
ALGORITHM
Step-6: Write each sorted lowercase word into the destination file.
93
PROGRAM
words = file.read().split()
words_lower.sort()
file.write("\n".join(words_lower))
# Example usage:
sort_words(input_filename, output_filename)
OUTPUT
VIVA QUESTIONS
1. How does your program handle reading from and writing to files in Python?
Ans.
2. What does the program do to ensure that all words in the output file are in lowercase?
Ans.
3. How do you sort words in the file? Explain the sorting algorithm or method used.
Ans.
4. Can you modify the program to handle files with very large sizes efficiently?
Ans.
Ans.
Python Programming
Experiment-19
Date:
PROGRAM-19
AIM
The aim is to read a file, reverse each line of text, and print each reversed line to the console.
ALGORITHM
Step-1: Open the file: Use Python’s open() function to open the file in read mode.
Step-2: Read lines: Use a loop to iterate through each line of the file.
Step-3: Reverse each line: For each line read, reverse its characters.
Step-4: Print reversed lines: Output each reversed line to the console.
Step-5: Close the file: Ensure the file is properly closed after reading.
PROGRAM
def print_lines_in_reverse(file_name):
try:
lines = file.readlines()
98
for line in reversed(lines):
reversed_line = line.strip()[::-1]
print(reversed_line)
except FileNotFoundError:
except IOError:
# Example usage:
print_lines_in_reverse(file_name)
OUTPUT
Hello, world!
This is line 2.
Another line.
.enil rehtonA
.2 enil si sihT
!dlrow ,olle
VIVA QUESTIONS
1. How does your program read each line from the file?
Ans.
Ans.
3. What is the expected output format when printing each line in reverse order?
Ans.
4. How does your program handle files with varying line lengths or empty lines?
Ans.
5. Can you explain any potential performance considerations for large files when
implementing this program?
Ans.
Python Programming
Experiment-20
Date:
PROGRAM-20
Python program to compute the number of characters, words and lines in a file.
AIM
The aim is to create a Python program that reads a file and computes the number of characters,
words, and lines present in that file.
ALGORITHM
def count_chars_words_lines(filename):
try:
num_chars = 0
num_words = 0
num_lines = 0
num_lines += 1
words = line.split()
num_words += len(words)
num_chars += len(line)
except FileNotFoundError:
print("File not found. Please check the file path and try again.")
except IsADirectoryError:
except Exception as e:
if __name__ == "__main__":
count_chars_words_lines(filename)
OUTPUT
Number of characters: 89
Number of words: 14
Number of lines
VIVA QUESTIONS
Ans.
2. What method do you use to count words? How do you define a word in your program?
Ans.
Ans.
Ans.
5. Can your program handle very large files efficiently? If so, how?
Ans.
Lab
Record
Experiment-21
Date:
PROGRAM-21
Write a program to create, display, append, insert and reverse the order of the items in the array.
AIM
To create a program that allows manipulation of a list including creating, displaying, appending,
inserting, and reversing its contents.
ALGORITHM
Step-3: Append Item: Add a new item to the end of the list.
Step-4: Insert Item: Insert a new item at a specified position in the list.
Step-6: Display List (Again): Print all items in the list after each operation to verify changes.
PROGRAM
def main():
my_list = []
my_list.append('apple')
my_list.insert(0, 'banana')
my_list.reverse()
if __name__ == "__main__":
main()
OUTPUT
VIVA QUESTIONS
1. What is the purpose of initializing my_list as an empty list at the beginning of the
program?
Ans.
2. How does the append method differ from the insert method when adding new items to a
list?
Ans.
3. What happens if you try to insert an item at an index that is out of range for the list?
Ans.
4. How does the reverse method change the order of elements in a list?
Ans.
Ans.
Lab
Record
Experiment-22
Date:
PROGRAM-22
AIM
To create a program that performs basic matrix operations such as addition, transpose, and
multiplication.
ALGORITHM
Step-1: Input Matrices: Prompt the user to enter dimensions and elements for two matrices.
Step-2: Matrix Addition: Add the two matrices if they are compatible (same dimensions).
Step-3: Matrix Transpose: Transpose a matrix to swap its rows with columns.
Step-4: Matrix Multiplication: Multiply two matrices if they are compatible (columns of the
first matrix equal rows of the second matrix).
Step-5: Display Results: Print the original matrices, result of addition, transpose, and
multiplication.
PROGRAM
matrix = []
111
for i in range(rows):
matrix.append(row)
return matrix
def display_matrix(matrix):
print(row)
result = []
for i in range(len(matrix1)):
row = []
for j in range(len(matrix1[0])):
row.append(matrix1[i][j] + matrix2[i][j])
result.append(row)
return result
def transpose_matrix(matrix):
result = []
for j in range(len(matrix[0])):
row = []
for i in range(len(matrix)):
row.append(matrix[i][j])
result.append(row)
return result
if cols1 != rows2:
for i in range(rows1):
for j in range(cols2):
for k in range(cols1):
return result
def main():
print("Matrix 1:")
print("\nMatrix 2:")
display_matrix(matrix1)
print("\nMatrix 2:")
display_matrix(matrix2)
print("\nMatrix Addition:")
display_matrix(addition_result)
else:
transpose_result = transpose_matrix(matrix1)
display_matrix(transpose_result)
print("\nMatrix Multiplication:")
if isinstance(multiplication_result, str):
print(multiplication_result)
else:
display_matrix(multiplication_result)
if __name__ == "__main__":
main()
OUTPUT
Matrix 1:
12
34
Matrix 2:
56
78
Matrix 1:
[1, 2]
[3, 4]
Matrix 2:
[5, 6]
[7, 8]
Matrix Addition:
[6, 8]
[10, 12]
Transpose of Matrix 1:
[1, 3]
[2, 4]
Matrix Multiplication:
[19, 22]
[43, 50]
VIVA QUESTIONS
Ans.
2. How do you perform matrix multiplication, and what are the necessary conditions for it?
Ans.
3. What are some potential edge cases to consider when working with matrices in
programming?
Ans.
4. How does the program handle invalid input or incompatible matrix dimensions?
Ans.
Ans.
Lab
Record
Experiment-23
Date:
PROGRAM-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.
AIM
To write a Python program that creates a class representing a shape, including methods to calculate
its area and perimeter, and implement subclasses for different shapes like circle, triangle, and
square.
ALGORITHM
Create a class called Shape with methods to calculate the area and perimeter. These
methods can be abstract or return a placeholder value since the exact calculation will
depend on the specific shape.
Create subclasses for Circle, Triangle, and Square, each inheriting from the Shape class.
Step-3: Implement methods in each subclass:
Override the methods to calculate the area and perimeter for each specific shape in its
respective subclass.
Step-4: Create instances and test
Create instances of each subclass and call the methods to calculate the area and perimeter.
Step-5: Display the results
PROGRAM
class Shape:
def area(self):
pass
def perimeter(self):
pass
class Circle(Shape):
self.radius = radius
def area(self):
return pi * self.radius**2
def perimeter(self):
return 2 * pi * self.radius
class Triangle(Shape):
self.b = b
self.c = c
def area(self):
def perimeter(self):
class Square(Shape):
self.side = side
def area(self):
return self.side**2
def perimeter(self):
return 4 * self.side
circle = Circle(5)
triangle = Triangle(3, 4, 5)
square = Square(4)
# Display the results
print("Circle:")
print(f"Area: {circle.area()}")
print(f"Perimeter: {circle.perimeter()}")
print("\nTriangle:")
print(f"Area: {triangle.area()}")
print(f"Perimeter: {triangle.perimeter()}")
print("\nSquare:")
print(f"Area: {square.area()}")
print(f"Perimeter: {square.perimeter()}")
OUTPUT
Circle:
Area: 78.53981633974483
Perimeter: 31.41592653589793
Triangle:
Area: 6.0
Perimeter: 12
Square:
Area: 16
Perimeter: 16
VIVA QUESTIONS
Ans.
Ans.
3. What are the differences between abstract classes and concrete classes?
Ans.
Ans.
Ans.
Python Programming
Experiment-24
Date:
PROGRAM-24
Write a Python program that checks whether a JSON string contains a complex object or not
AIM
To write a Python program that checks whether a JSON string contains a complex object or not.
ALGORITHM
import json
def is_complex(json_str):
try:
obj = json.loads(json_str)
except json.JSONDecodeError:
return False
def check_complexity(obj):
if isinstance(obj, dict):
return True
return True
return False
return check_complexity(obj)
# Test cases
OUTPUT
Is complex: False
Is complex: True
VIVA QUESTIONS
Ans.
Ans.
3. What Python libraries are commonly used for working with JSON?
Ans.
Ans.
Ans.
Lab
Record
Experiment-25
Date:
PROGRAM-25
AIM
ALGORITHM
Step-2: Use the numpy.array() function to create different types of NumPy arrays:
PROGRAM
import numpy as np
125
# Creating a 2-dimensional array
print("1-dimensional array:")
print(arr1)
print("\n2-dimensional array:")
print(arr2)
print(arr3)
OUTPUT
VIVA QUESTIONS
Ans.
2. What is a NumPy array and how does it differ from a Python list?
Ans.
Ans.
Ans.
Ans.
Lab
Record
Experiment-26
Date:
PROGRAM-26
AIM
To demonstrate the use of ndim, shape, size, and dtype attributes in Python to understand the
dimensions, shape, size, and data type of NumPy arrays.
ALGORITHM
Step-3: Print the attributes ndim, shape, size, and dtype of the array.
PROGRAM
import numpy as np
129
# Displaying the attributes
print("Array:")
print(arr)
print("\nAttributes:")
print("Shape:", arr.shape)
print("Size:", arr.size)
OUTPUT
VIVA QUESTIONS
1. What does the ndim attribute of a NumPy array represent and how is it used?
Ans.
2. How can you find the shape of a NumPy array using the shape attribute?
Ans.
Ans.
4. How do you check the data type of elements in a NumPy array using the dtype attribute?
Ans.
5. Write syntaxes of ndim, shape, size, dtype in the context of NumPy arrays?
Ans.
Lab
Record
Experiment-27
Date:
PROGRAM-27
AIM
To demonstrate basic slicing, integer indexing, and Boolean indexing in Python lists.
ALGORITHM
133
PROGRAM
def demonstrate_basic_slicing():
print()
def demonstrate_integer_indexing():
print()
def demonstrate_boolean_indexing():
numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
print()
def main():
demonstrate_basic_slicing()
demonstrate_integer_indexing()
demonstrate_boolean_indexing()
if __name__ == "__main__":
main()
OUTPUT
Original List: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Filtered Numbers (numbers > 50): [60, 70, 80, 90, 100]
VIVA QUESTIONS
1. What is slicing in NumPy, and how is it different from slicing in regular Python lists?
Ans.
Ans.
3. What is integer indexing in NumPy, and how does it differ from basic slicing?
Ans.
4. How is Boolean indexing used in NumPy, and what are its typical use cases?
Ans.
5. Write Syntaxes of slicing, integer indexing, and Boolean indexing in NumPy array?
Ans.
Lab
Record
Experiment-28
Date:
PROGRAM-28
AIM
To compute and display the minimum value, maximum value, sum, and cumulative sum of
elements in an array.
ALGORITHM
Initialize variables min_value and max_value with the first element of the array.
Iterate through the array to update min_value and max_value as needed.
Step-3: Calculate Sum of Array
Step-5: Display Results: Print the minimum value, maximum value, sum, and cumulative sum.
137
PROGRAM
# Python program to find min, max, sum, and cumulative sum of an array
def array_operations(arr):
# Initialize variables
min_value = arr[0]
max_value = arr[0]
array_sum = 0
cumulative_sum = []
current_cumulative_sum = 0
min_value = num
max_value = num
array_sum += num
current_cumulative_sum += num
cumulative_sum.append(current_cumulative_sum)
# Display results
# Example usage:
if __name__ == "__main__":
array = [5, 2, 9, 1, 7, 3]
array_operations(array)
OUTPUT
Minimum Value: 1
Maximum Value: 9
Sum of Array: 27
1. How do you find the minimum value in a NumPy array using a built-in function?
Ans.
2. What function would you use to determine the maximum value in a NumPy array?
Ans.
3. How can you calculate the sum of all elements in a NumPy array?
Ans.
4. What is the purpose of the cumsum function in NumPy, and how does it work?
Ans.
5. Wrie the use NumPy to find the cumulative sum of a 2D array along different axes?
Ans.
Lab
Record
Experiment-29
Date:
PROGRAM-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.
AIM
To create a dictionary with at least five keys, where each key has a list of at least ten values,
convert this dictionary into a Pandas DataFrame, and explore the data using the DataFrame’s
head() function and various data selection operations.
ALGORITHM
Use the head() function to view the first few rows of the DataFrame.
Perform various data selection operations, such as selecting specific columns, rows, or
subsets of the DataFrame.
PROGRAM
import pandas as pd
data = {
'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)
print(df.head())
print("\nColumn 'B':")
print(df['B'])
print(df[['A', 'C']])
print(df.iloc[2])
print(df.iloc[1:4])
OUTPUT
A B C D E
0 1 11 21 31 41
1 2 12 22 32 42
2 3 13 23 33 43
3 4 14 24 34 44
4 5 15 25 35 45
Column 'B':
0 11
1 12
2 13
3 14
4 15
5 16
6 17
7 18
8 19
9 20
A C
0 1 21
1 2 22
2 3 23
3 4 24
4 5 25
5 6 26
6 7 27
7 8 28
8 9 29
9 10 30
A 3
B 13
C 23
D 33
E 43
A B C D E
1 2 12 22 32 42
2 3 13 23 33 43
3 4 14 24 34 44
A B C D E
5 6 16 26 36 46
6 7 17 27 37 47
7 8 18 28 38 48
8 9 19 29 39 49
9 10 20 30 40 50
VIVA QUESTIONS
1. How do you create a dictionary in Python, and what are some common data types that
can be used as values in a dictionary?
Ans.
Ans.
3. Write Syntaxes of head() function in Pandas, and how does it help in exploring the initial
rows of a DataFrame?
Ans.
4. What are some common methods and attributes used for data selection in a Pandas
DataFrame?
Ans.
5. How would you select specific columns from a Pandas DataFrame, and what methods
would you use for slicing rows based on specific conditions?
Ans.
Python Programming
Experiment-30
Date:
PROGRAM-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
AIM
To observe the relationship between two selected columns from a Pandas DataFrame by
creating a scatter plot using Matplotlib.
ALGORITHM
Step-1: Create a Pandas DataFrame: Initialize a dictionary with at least five keys, where
each key represents a list with at least ten values.
Step-3: Select Columns: Choose any two columns from the DataFrame.
Step-4: Plotting: Use Matplotlib to create a scatter plot where one column is plotted against
the other.
Step-5: Observation: Analyze the scatter plot to observe any relationship or pattern between
the two variables.
PROGRAM
import pandas as pd
# Step 1: Create a dictionary with at least five keys and lists of at least ten values each
data = {
'A': [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
'B': [5, 15, 25, 35, 45, 55, 65, 75, 85, 95],
'C': [12, 24, 36, 48, 60, 72, 84, 96, 108, 120],
'D': [8, 16, 24, 32, 40, 48, 56, 64, 72, 80],
df = pd.DataFrame(data)
column1 = 'A'
column2 = 'B'
plt.figure(figsize=(8, 6))
plt.xlabel(column1)
plt.ylabel(column2)
plt.legend()
plt.grid(True)
plt.show()
Output:
The scatter plot will display a graph where values from column 'A' are plotted against
values from column 'B'. Each point represents a pair of values from the two columns,
showing their relationship visually.
VIVA QUESTIONS
1. How do you select specific columns from a Pandas DataFrame, and what methods would
you use to ensure data integrity when working with selected columns?
Ans.
2. What is the purpose of a scatter plot in data visualization, and how does it differ from
other types of plots?
Ans.
3. How to create a scatter plot using Matplotlib, and what parameters are essential for
plotting two variables against each other?
Ans.
4. How would you interpret the relationship between two variables based on a scatter plot
generated from a Pandas DataFrame?
Ans.
5. What are some advantages of using Matplotlib for data visualization, and how can you
customize plots to improve readability and understanding?
Ans.