Python Lab Manual Final
Python Lab Manual Final
PYTHON PROGRAMMING
[1BPLC105B/205B]
(CBCS SCHEME)
B.E-II Semester
Lab Manual 2025-26
Name:
USN:
Batch: Section:
Department of Artificial Intelligence
and Data Science
PYTHON PROGRAMMING
[1BPLC105B/205B]
Prepared By Approved By
Aishwarya N M [Link] S
Faculty In-charge HOD, AI&DS
INSTITUTIONAL MISSION AND VISION
M1:To engage students in developing core competencies to solve real-world problems using
Artificial Intelligence.
M2:To enlighten students into becoming technically proficient engineers through innovation
and application in Data Science.
M3:To involve students in industry collaborations, career development,and the cultivation of
leadership skills.
M4:To mold students into ethical professionals who up hold moral values for the betterment of
individuals and society.
After4yearsofgraduation,graduateswillbeableto
PEO1: To develop in students, the ability to solve real life problems by applying fundamental
science and elementary strengths of computer science courses.
PEO2: To mould students, to have a successful career in the IT industry where graduates will
be able to design and implement the needs of society and nation.
PEO3:To transform students,to excel in a competitive world through higher education and indulge in
research through continuous learning process.
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 analyze 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, andmodern
engineering and IT tools including prediction and modelling to complex engineering activities with
an understanding of the limitations.
PO6: TheEngineerandSociety: Applyreasoning informed bythecontextualknowledgetoassess
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
leaderin 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 principle sand apply these to one’s own work, as a member and leader
in a team, to manage projects and in multidisciplinary environments.
PO12:Life-LongLearning: 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.
SYLLABUS
PYTHON PROGRAMMING
[Link] Experiments
1. 1. a. Develop a python program to read 2 numbers from the keyboard and perform the
basic arithmetic operations based on the choice. (1-Add, 2-Subtract, 3-Multiply, 4-
Divide).
b. Develop a program to read the name and year of birth of a person. Display whether
the person is a senior citizen or not.
2. 2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from
the console.
b. Write a python program to create a list and perform the following operations
• Inserting an element
• Removing an element
• Appending an element
• Displaying the length of the list
• Popping an element
• Clearing the list
3. a. Read N numbers from the console and create a list. Develop a program to print
mean, variance and standard deviation with suitable messages.
b. Read a multi-digit number (as chars) from the console. Develop a program to print
the frequency of each digit with a suitable message.
4. Develop a program to print 10 most frequently appearing words in a text file. [Hint:
Use a dictionary with distinct words and their frequency of occurrences. Sort the
dictionary in the reverse order of frequency and display the dictionary slice of the first
10 items.
5. Develop a program to read 6 subject marks from the keyboard for a student. Generate a
report that displays the marks from the highest to the lowest score attained by the
student. [Read the marks into a 1-Dimesional array and sort using the Bubble Sort
technique].
6. Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file. [Hint: Use string methods strip(), len(), list methods sort(), append(),
and file methods open(), readlines(), and write()].
7. Develop a function named DivExp which takes TWO parameters a, b, and returns a
value c (c=a/b). Write a suitable assertion for a>0 in the function DivExp and raise an
exception for when b=0. Develop a suitable program that reads two console values and
calls the function DivExp.
8. Define a function that takes TWO objects representing complex numbers and returns a
new complex number with the sum of two complex numbers. Define a suitable class
‘Complex’ to represent the complex number. Develop a program to read N (N >=2)
complex numbers and to compute the addition of N complex numbers.
9. Text Analysis Tool: Build a tool that analyses a paragraph: frequency of each word,
longest word, number of sentences, etc.
10. Develop Data Summary Generator: Read a CSV file (like COVID data or weather
stats), convert to dictionary form, and allow the user to run summary queries: max,
min, average by column.
11. Develop Student Grade Tracker: Accept multiple students’ names and marks. Store
them in a list of tuples or dictionaries. Display summary reports (average, topper, etc.).
12. Develop a program to display contents of a folder recursively (Directory) having sub-
folders and files (name and type).
Course outcome (Course Skill Set)
At the end of the course, the student will be able to:
CO1: Develop scripts using primitive language constructs of python.
CO2: Identify the methods to manipulate primitive python data structures.
CO3: Make use of Python standard libraries for programming.
CO4: Build scripts for performing file operations.
CO5: Illustrate the concepts of Object-Oriented Programming as used in Python.
Assessment Structure (IPCC): (Circular-Ref.: VTU/BGM/IPCC 2025/3748, DATED: 24TH Oct 2025)
The assessment for each course is equally divided between Continuous Internal Evaluation (CIE) and the
Semester End Examination (SEE), with each component carrying 50% weightage (i.e., 50 marks each).
The CIE Theory component will be 25 marks and CIE Practical component will be 25 marks.
The CIE Theory component consists of IA tests for 25 marks. The CIE Practical component for continuous
assessments will be for 15 marks through rubrics and for lab Internal Assessment will be conducted for 10
marks through rubrics.
. • To qualify and become eligible to appear for SEE, in the CIE theory component, a student must score at
least 40% of 25 marks, i.e., 10 marks.
• To qualify and become eligible to appear for SEE, in the CIE Practical component, a student must secure a
minimum of 40% of 25marks, i.e., 10marks.
• To pass the SEE, a student must secure a minimum of 35% of 50 marks, i.e., 18 marks.
A student is deemed to have completed the course if the combined total of CIE and SEE is at least 40 out of
100 marks.
3. Students should come with formals and to be present on time in the laboratory.
4. Students will not be permitted to attend the laboratory unless they bring the
practical record fully completed in all respects pertaining to the experiments
conducted in the previous session.
5. Students will be permitted to attend the laboratory unless they bring the
observation book fully completed in all respects pertaining to the
experiments conducted in the present session.
6. They should obtain the signature of the staff-in –charge in the observation
book after completing each experiment.
7. Practical record should be neatly maintained.
8. Ask lab Instructor for assistance for any problem.
9. Do not download or install software with out the assistance of laboratory
Instructor.
10. Do not alter the configuration of system.
11. Turn off the systems after use.
PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)
1)
Output: 1)
Enter First Number: 12
1). b) Develop a program to read the name and year of birth of a person. Display
whether the person is a senior citizen or not.
Objective : To develop a Python program to check whether a person is a senior
citizen based on their year of birth.
current_year = [Link]().year
age = current_year - birth_year
if(age>=60 ):
print( f"{name} is a senior citizen")
else:
print( f"{name} Not a senior citizen")
Output:
1) Enter year of birth: 1950
Enter the name: Alice
Alice is a senior citizen
2) Enter year of birth: 1987
Enter the name: Bob
Bob Not a senior citizen
Output:
Enter the Fibonacci sequence length to be generated: 8
The Fibonacci series with 8 terms is:
0 1 1 2 3 5 8 13
2). b) Write a python program to create a list and perform the following
operations
Inserting an element
Removing an element
Appending an element
Displaying the length of the list
Popping an element
Clearing the list
Objective: To create a Python program to perform basic operations on a list.
popped_element = my_list.pop()
print(f"Popped element (last): {popped_element}")
print(f"List after popping last element: {my_list}")
# Pop an element at a specific index (e.g., index 0)
if my_list: # Check if list is not empty before popping by index
popped_at_index = my_list.pop(0)
print(f"Popped element at index 0: {popped_at_index}")
print(f"List after popping element at index 0: {my_list}")
else:
print("List is empty, cannot pop by index.")
# 6. Clearing the list
my_list.clear()
print(f"After clearing the list: {my_list}”)
Output:
Initial list: [10, 20, 30, 40, 50]
After inserting 15 at index 1: [10, 15, 20, 30, 40, 50]
After removing 30: [10, 15, 20, 40, 50]
After appending 60: [10, 15, 20, 40, 50, 60]
Length of the list: 6
Popped element (last): 60
List after popping last element: [10, 15, 20, 40, 50]
Popped element at index 0: 10
List after popping element at index 0: [15, 20, 40, 50]
After clearing the list: []
Outcome : Learned to use list methods like insert, remove, append, pop, clear,
and find the length of a list in python.
3)
a) Read N numbers from the console and create a list. Develop a program to
print mean, variance and standard deviation with suitable messages.
Objective: To develop a Python program to calculate the mean, variance, and
standard deviation of N numbers.
import math
# Read number of elements
n = int(input("Enter the number of values (N): "))
# Initialize empty list
numbers = []
# Read N numbers from user
print(f"Enter {n} numbers:")
for i in range(n):
num = float(input(f"Number {i+1}: "))
[Link](num)
# Calculate mean
mean = sum(numbers) / n
# Calculate variance
variance = sum((x - mean) ** 2 for x in numbers) / n
# Calculate standard deviation
standard_deviation = [Link](variance)
# Display results
print(f"Mean: {mean:.2f}")
print(f"Variance: {variance:.2f}")
print(f"Standard Deviation: {standard_deviation:.2f}")
Output:
Enter the number of values (N): 4
Enter 4 numbers:
Number 1: 45
Number 2: 45
Number 3: 65
Number 4: 23
Mean: 44.50
Variance: 220.75
Standard Deviation: 14.86
3) b) Read a multi-digit number (as chars) from the console. Develop a program
to print the frequency of each digit with a suitable message.
Objective:To develop a Python program to find the frequency of each digit in a
given multi-digit number
Outcome : Learned to process characters and count the occurrence of each digit
using loops and logic in Python.
word_freq[word] = 1
# Sort the dictionary by frequency (descending)
sorted_freq = sorted(word_freq.items(), key=lambda item: item[1],
reverse=True)
# Print the top 10 most frequent words
print("\n--- Top 10 Most Frequent Words ---")
for word, freq in sorted_freq[:10]:
print(f"'{word}': {freq} time(s)")
except FileNotFoundError:
print("Error: File not found.")
except Exception as e:
print(f"An error occurred: {e}")
Output:
Enter the file name (with extension): [Link]
--- Top 10 Most Frequent Words ---
'the': 45 time(s)
'and': 30 time(s)
'to': 25 time(s)
'of': 22 time(s)
'a': 20 time(s)
'in': 18 time(s)
'is': 15 time(s)
'that': 12 time(s)
'it': 10 time(s)
'with': 9 time(s)
Outcome: Learned to read a file, count word frequencies using a dictionary, sort
the data, and display the top 10 frequent words in Python.
5) Develop a program to read 6 subject marks from the keyboard for a student.
Generate a report that displays the marks from the highest to the lowest score
attained by the student. [Read the marks into a 1-Dimesional array and sort
using the Bubble Sort technique].
Objective: To develop a Python program to read six subject marks into a one-
dimensional array and sort them in descending order using the Bubble Sort
technique.
def bubble_sort_desc(arr):
n = len(arr)
# Bubble Sort algorithm for descending order
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] < arr[j + 1]: # Swap if the element is smaller than the next
arr[j], arr[j + 1] = arr[j + 1], arr[j]
# Step 1: Read marks from the user
marks = []
print("Enter marks for 6 subjects:")
for i in range(6):
mark = float(input(f"Subject {i + 1}: "))
[Link](mark)
# Step 2: Sort marks using Bubble Sort in descending order
bubble_sort_desc(marks)
# Step 3: Display the sorted marks
print("\nReport: Marks from Highest to Lowest")
for i, mark in enumerate(marks, start=1):
print(f"{i}. {mark}")
Output:
Enter marks for 6 subjects:
Subject 1: 45
Subject 2: 75
Subject 3: 5
Subject 4: 55
Subject 5: 33
Subject 6: 22
Report: Marks from Highest to Lowest
1. 75.0
2. 55.0
3. 45.0
4. 33.0
5. 22.0
6. 5.0
Outcome: Students will be able to implement Bubble Sort and display the marks
from highest to lowest correctly.
6) Develop a python program to sort the contents of a text file and write the
sorted contents into a separate text file. [Hint: Use string methods strip(), len(),
list methods sort(), append(), and file methods open(), readlines(), and write()].
Objective:To develop a Python program to read the contents of a text file, sort
them using list and string methods, and write the sorted data into a separate text
file.
def sort_file_contents(input_file, output_file):
try:
# Open the input file and read all lines
with open(input_file, 'r') as infile:
lines = [Link]()
# Strip whitespace and store in a list
clean_lines = []
for line in lines:
stripped_line = [Link]()
if len(stripped_line) > 0: # Optional: skip empty lines
clean_lines.append(stripped_line)
# Sort the list alphabetically
clean_lines.sort()
# Write the sorted lines to the output file
with open(output_file, 'w') as outfile:
for line in clean_lines:
[Link](line + '\n')
print(f"File '{input_file}' sorted successfully into '{output_file}'.")
except FileNotFoundError:
Outcome: Students will be able to perform file handling operations and apply
sorting techniques using string and list methods in Python.
print(f"Error: {zde}")
except ValueError:
print("Invalid input. Please enter numeric values.")
except Exception as e:
print(f"An unexpected error occurred: {e}")
# Run the main program
if __name__ == "__main__":
main()
8) Define a function that takes TWO objects representing complex numbers and
returns a new complex number with the sum of two complex numbers. Define a
suitable class ‘Complex’ to represent the complex number. Develop a program
to read N (N >=2) complex numbers and to compute the addition of N complex
numbers.
class Complex:
def __init__(self, real, imag):
[Link] = real
[Link] = imag
def add(self, other):
return Complex([Link] + [Link], [Link] + [Link])
def display(self):
print(f"{[Link]} + {[Link]}i")
N = int(input("How many complex numbers? (N >= 2): "))
if N < 2:
print("Please enter at least 2 complex numbers.")
else:
print("Enter real and imaginary parts:")
real = float(input("Real part of number 1: "))
imag = float(input("Imag part of number 1: "))
total = Complex(real, imag)
for i in range(2, N + 1):
real = float(input(f"Real part of number {i}: "))
imag = float(input(f"Imag part of number {i}: "))
Outcome: Students will be able to implement classes, create objects, and perform
operations on user-defined data types in Python.
9) Text Analysis Tool: Build a tool that analyses a paragraph: frequency of each
word, longest word, number of sentences, etc.
Objective: To develop a Python program that analyzes a paragraph to determine
word frequency, longest word, and number of sentences using string processing
techniques.
def analyze_paragraph(text):
# Split sentences by '.', '!' or '?'
sentences = [Link]('!', '.').replace('?', '.').split('.')
sentences = [[Link]() for s in sentences if [Link]()]
num_sentences = len(sentences)
# Split words
words = [Link]()
num_words = len(words)
# Word frequencies (case-insensitive)
word_freq = {}
for word in words:
clean_word = [Link]('.,!?').lower()
if clean_word:
word_freq[clean_word] = word_freq.get(clean_word, 0) + 1
# Longest word
longest_word = ''
for word in words:
clean_word = [Link]('.,!?')
if len(clean_word) > len(longest_word):
longest_word = clean_word
print(f"Number of sentences: {num_sentences}")
print(f"Number of words: {num_words}")
print(f"Longest word: {longest_word}")
print("\nWord Frequencies:")
for word, freq in word_freq.items():
print(f" {word}: {freq}")
paragraph = input("Enter a paragraph:\n")
analyze_paragraph(paragraph)
10) Develop Data Summary Generator: Read a CSV file (like COVID data or
weather stats), convert to dictionary form, and allow the user to run summary
queries: max, min, average by column.
Objective: To develop a Python program that reads data from a CSV file, converts
it into dictionary format, and generates summary statistics such as maximum,
minimum, and average for selected columns.
import csv
def read_csv(filename):
with open(filename) as f:
reader = [Link](f)
return list(reader)
def get_numbers(data, column):
numbers = []
for row in data:
try:
[Link](float(row[column]))
except:
pass
return numbers
def main():
filename = input("CSV filename: ")
data = read_csv(filename)
if not data:
print("File is empty or not found.")
return
columns = data[0].keys()
print("Columns in csv file:\n", "\n".join(columns))
while True:
col = input("Enter column name (or 'exit' to quit): ")
if col == 'exit':
break
if col not in columns:
print("Invalid column name.")
continue
op = input("Operation (max, min, average): ").lower()
nums = get_numbers(data, col)
if not nums:
print("No numeric data found in this column.")
continue
if op == 'max':
print("Max:", max(nums))
elif op == 'min':
print("Min:", min(nums))
elif op == 'average':
print("Average:", sum(nums)/len(nums))
else:
print("Invalid operation.")
if __name__ == "__main__":
main()
Output:
CSV filename: [Link]
Columns in csv file:
[Link]
[Link]
[Link]
[Link]
[Link]
Avg Temp
Max Temp
Min Temp
[Link]
[Link]
Enter column name (or 'exit' to quit): Min Temp
Operation (max, min, average):
max Max: 74.0
Outcome: Students will be able to perform CSV file handling, use dictionaries for
data representation, and compute statistical summaries using Python.
11) Develop Student Grade Tracker: Accept multiple students’ names and
marks. Store them in a list of tuples or dictionaries. Display summary reports
(average, topper, etc.).
Objective: To develop a Python program that accepts multiple students' names
and marks, stores them using lists and dictionaries, and generates summary
reports such as average marks and topper.
students = []
while True:
name = input("Enter student name (or 'done' to stop): ")
if [Link]() == 'done':
break
marks = input("Enter marks: ")
try:
marks = float(marks)
except:
print("Please enter a number for marks.")
continue
[Link]((name, marks))
if not students:
print("No students entered.")
else:
total = sum(m[1] for m in students)
average = total / len(students)
topper = max(students, key=lambda x: x[1])
print(f"\nNumber of students: {len(students)}")
Output:
Enter student name (or 'done' to stop): Alice
Enter marks: 55
Enter student name (or 'done' to stop): Bob
Enter marks: 36
Enter student name (or 'done' to stop): Mary
Enter marks: 45
Enter student name (or 'done' to stop): John
Enter marks: 78
Enter student name (or 'done' to stop): done
Number of students: 4
Average marks: 53.50
Topper: John with marks 78.0
Outcome: Students will be able to use lists, tuples, and dictionaries to store data
and perform basic analysis like calculating averages and identifying the highest
scorer.
Output:
Enter folder path: D:\CSE\CSE\Example
Contents of 'D:\CSE\CSE\Example':
� [Link]
� [Link]
� [Link]
� N/
Outcome: Students will be able to work with directories, identify file types, and
implement recursive functions in Python.
Viva Questions
1. What is Python?
Answer: Python is a high-level, interpreted programming language that is easy to learn and
widely used for web development, data analysis, AI, and automation.
2. What are the features of Python?
Answer: Python is simple, readable, interpreted, portable, and supports object-oriented
programming.
3. What is a variable in Python?
Answer: A variable is a name used to store data values in a program.
4. How do you take input from the user in Python?
Answer: Using the input() function.
Example:
num = int(input("Enter a number"))
5. What are arithmetic operators in Python?
Answer: + (addition), - (subtraction), * (multiplication), / (division), % (modulus), ** (power), //
(floor division).
6. What is an if statement?
Answer: It is used for decision making in a program.
Example:
if age >= 60:
print("Senior Citizen")
7. What is a loop?
Answer: A loop is used to execute a block of code repeatedly.
8. What are the types of loops in Python?
Answer: for loop and while loop.
9. What is the Fibonacci sequence?
Answer: A sequence where each number is the sum of the two previous numbers.
Example: 0, 1, 1, 2, 3, 5, 8.
10. What is a list in Python?
Answer: A list is a collection of elements stored in a single variable using square brackets.
Example:
numbers = [1,2,3,4]
11. What is the difference between list and tuple?
Answer:
List → Mutable (can change).
Tuple → Immutable (cannot change).
12. What does append() do in a list?
Answer: It adds an element at the end of the list.
Example:
[Link](10)
13. What does insert() do?
Answer: It inserts an element at a specified position.
Example:
[Link](1,5)
14. What does pop() do?
Answer: It removes and returns the last element from the list.
15. How do you find the length of a list?
Answer: Using len() function.
Example:
len(list)
16. What is mean?
Answer: Mean is the average value of numbers.
Formula:
Mean = Sum of values / Number of values.
17. What is variance?
Answer: Variance measures how far numbers are spread from the mean.
18. What is standard deviation?
Answer: Standard deviation is the square root of variance and shows data variation.
19. What is a dictionary in Python?
Answer: A dictionary stores data in key-value pairs.
Example:
student = {"name":"Ravi", "marks":90}
20. What is Bubble Sort?
Answer: Bubble Sort is a sorting algorithm that repeatedly compares and swaps adjacent
elements.
21. What is file handling?
Answer: File handling is used to read and write data to files.
22. What is the syntax to open a file?
Answer:
file = open("[Link]","r")
23. What does readlines() do?
Answer: It reads all lines from a file and returns them as a list.
24. What does write() do?
Answer: It writes data into a file.
25. What is a function?
Answer: A function is a block of code that performs a specific task.
Example:
def add(a,b):
return a+b
26. What is an assertion in Python?
Answer: Assertion is used to check if a condition is true.
Example:
assert a > 0
27. What is exception handling?
Answer: It is used to handle runtime errors in a program.
28. What is a class in Python?
Answer: A class is a blueprint for creating objects.
29. What is an object?
Answer: An object is an instance of a class.
Example:
obj = Complex()