0% found this document useful (0 votes)
6 views45 pages

Python Lab Manual Final

The document is a lab manual for a Python programming course under the Department of Artificial Intelligence and Data Science for the B.E-II Semester. It outlines the course objectives, educational outcomes, practical experiments, assessment structure, and suggested learning resources. The manual includes various programming tasks aimed at developing core competencies in Python, such as arithmetic operations, list manipulations, and data analysis.

Uploaded by

deekshithrm548
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views45 pages

Python Lab Manual Final

The document is a lab manual for a Python programming course under the Department of Artificial Intelligence and Data Science for the B.E-II Semester. It outlines the course objectives, educational outcomes, practical experiments, assessment structure, and suggested learning resources. The manual includes various programming tasks aimed at developing core competencies in Python, such as arithmetic operations, list manipulations, and data analysis.

Uploaded by

deekshithrm548
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

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]

(PRACTICAL COMPONENT OF IPCC)

Prepared By Approved By

Aishwarya N M [Link] S
Faculty In-charge HOD, AI&DS
INSTITUTIONAL MISSION AND VISION

VISION OF THE DEPARTMENT

“To impart value-based education and nurture idealistic, ethical engineers


equippedtomeettheevolving trends and technological advancements in the field of Artificial
Intelligence and Data Science”
MISSION OF THE DEPARTMENT

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.

PROGRAM EDUCATIONAL OBJECTIVES (PEOs)

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.

PROGRAM SPECIFIC OUTCOMES(PSOs)


At the end of the program, graduates will be able to
PSO1: Apply engineering principles, professional ethics and fundamental science in designing
systems and communication models (protocols).
PSO2:Design and develop smart and intelligent based applications in computational environment.
Department of Artificial Intelligence & Data Science

SYLLABUS
PYTHON PROGRAMMING

PRACTICAL COMPONENT OF IPCC


[As per Choice Based Credit System (CBCS) scheme]
SEMESTER – II (AD)

Subject Code:BCS403 CIE Marks:25


Hours/Week :02(02Hours Laboratory) Test Hours:03

Using suitable simulation software,demonstrate the operation of the following programs:

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

Suggested Learning Resources:


Text Books:
Text books: 1. Peter Wentworth, Jeffrey Elkner, Allen B. Downey and Chris Meyers- How to think like a
computer scientist: learning with python 3. Green Tea Press, Wellesley, Massachusetts,2020
[Link]
Reference books / Manuals:
1. Al Sweigart,“ Automate the Boring Stuff with Python, 2nd Edition: Practical Programming for Total
Beginners”,2nd Edition, No Starch Press, 2022. (Available under CC-BY-NC-SA license at
[Link]
2. Kyla McMullen, Elizabeth Matthews and June Jamrich Parsons, Programming with Python, Cengage, 2023
General Instructions to Students

1. Students should come with thorough preparation for the experiment to be


conducted.
2. Students should take prior permission from the concerned faculty before
availing the leave.

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)

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).
Objective:To develop a Python program to perform basic arithmetic operations
based on user choice.
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
print("Enter which operation would you like to perform?")
ch = input("Enter any of these char for specific operation +,-,*,/: ")
result = 0
if ch == '+':
result = num1 + num2
elif ch == '-':
result = num1 - num2
elif ch == '*':
result = num1 * num2
elif ch == '/':
result = num1 / num2
else:
print("Input character is not recognized!")
print(num1, ch , num2, ":", result)

Output: 1)
Enter First Number: 12

Dept. of AI&DS,AIT,Tumkur Page 1


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

Enter Second Number: 12


Enter which operation would you like to perform?
Enter any of these char for specific operation +,-,*,/: *
12 * 12 : 144
2) Enter First Number: 12
Enter Second Number: 12
Enter which operation would you like to perform?
Enter any of these char for specific operation +,-,*,/: +
12 + 12 : 24
Outcome: Learned to read input from the user and perform arithmetic operations
using conditional statements in Python.

Dept. of AI&DS,AIT,Tumkur Page 2


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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.

from datetime import datetime

birth_year=int(input("Enter year of birth: "))


name=input("Enter the name:")

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

Outcome: Learned to use input and conditional statements in Python to


determine if a person is a senior citizen.

Dept. of AI&DS,AIT,Tumkur Page 3


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

2). a) Develop a program to generate Fibonacci sequence of length (N). Read N


from the console.
Objective:To develop a Python program to generate the Fibonacci sequence for a
given number N

num = int(input("Enter the Fibonacci sequence length to be generated: "))


firstTerm = 0
secondTerm = 1
print("The Fibonacci series with", num, "terms is:")
print(firstTerm, secondTerm, end=" ")
for i in range(2, num):
curTerm = firstTerm + secondTerm
print(curTerm, end=" ")
firstTerm = secondTerm
secondTerm = curTerm
print()

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

Outcome:Learned to use loops and logic in Python to generate the Fibonacci


sequence up to N terms.

Dept. of AI&DS,AIT,Tumkur Page 4


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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.

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


print(f"Initial list: {my_list}")
# 1. Removing an element
my_list.insert(1, 15)
print(f"After inserting 15 at index 1: {my_list}")
# 2. Removing an element
my_list.remove(30)
print(f"After removing 30: {my_list}")
# 3. Appending an element
my_list.append(60)
print(f"After appending 60: {my_list}")
# 4. Displaying the length of the list
list_length = len(my_list)
print(f"Length of the list: {list_length}")
# 5. Popping an element

Dept. of AI&DS,AIT,Tumkur Page 5


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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

Dept. of AI&DS,AIT,Tumkur Page 6


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

Outcome : Learned to use list methods like insert, remove, append, pop, clear,
and find the length of a list in python.

Dept. of AI&DS,AIT,Tumkur Page 7


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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

Dept. of AI&DS,AIT,Tumkur Page 8


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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

Outcome: Outcome: Learned to use lists and mathematical calculations in Python


to compute mean, variance, and standard deviation.

Dept. of AI&DS,AIT,Tumkur Page 9


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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

# Read input from user


number = input("Enter a multi-digit number: ")
# Initialize a dictionary to store digit frequencies
digit_count = {}
# Iterate through each character in the input
for char in number:
if [Link](): # Only process digits
if char in digit_count:
digit_count[char] += 1
else:
digit_count[char] = 1
else:
print(f"Ignoring non-digit character: '{char}'")
# Print frequency of each digit
print("\n--- Digit Frequencies ---")
for digit in sorted(digit_count.keys()):
print(f"Digit {digit} occurs {digit_count[digit]} time(s)")
Output:
Enter a multi-digit number: 5533534655
--- Digit Frequencies ---

Dept. of AI&DS,AIT,Tumkur Page 10


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

Digit 3 occurs 3 time(s)


Digit 4 occurs 1 time(s)
Digit 5 occurs 5 time(s)
Digit 6 occurs 1 time(s)

Outcome : Learned to process characters and count the occurrence of each digit
using loops and logic in Python.

Dept. of AI&DS,AIT,Tumkur Page 11


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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 thedictionary in the reverse order of frequency and display the dictionary
slice of the first 10 items.
Objective:To develop a Python program to find and display the 10 most
frequently occurring words in a text file using a dictionary.

file_name = input("Enter the file name (with extension): ")


try:
# Open and read the file
with open(file_name, 'r', encoding='utf-8') as file:
text = [Link]()
# Normalize the text: convert to lowercase and remove punctuation
import string
text = [Link]()
for punct in [Link]:
text = [Link](punct, '')
# Split text into words
words = [Link]()
# Create a dictionary to count word frequencies
word_freq = {}
for word in words:
if word in word_freq:
word_freq[word] += 1
else:

Dept. of AI&DS,AIT,Tumkur Page 12


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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)

Dept. of AI&DS,AIT,Tumkur Page 13


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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

Dept. of AI&DS,AIT,Tumkur Page 14


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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

Dept. of AI&DS,AIT,Tumkur Page 15


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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.

Dept. of AI&DS,AIT,Tumkur Page 16


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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:

Dept. of AI&DS,AIT,Tumkur Page 17


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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


except Exception as e:
print(f"An error occurred: {e}")
# Example usage
if __name__ == "__main__":
input_filename = "[Link]"
output_filename = "sorted_output.txt"
sort_file_contents(input_filename, output_filename)
Output: :File '[Link]' sorted successfully into 'sorted_output.txt'
[Link] sorted_output.txt
Banana Banana
apple Cherry
Cherry apple

Outcome: Students will be able to perform file handling operations and apply
sorting techniques using string and list methods in Python.

Dept. of AI&DS,AIT,Tumkur Page 18


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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.
Objective: To develop a Python function DivExp(a, b) that performs division with
assertion for positive numerator and exception handling for division by zero.

def DivExp(a, b):


# Assert that a is greater than 0
assert a > 0, "Value of 'a' must be greater than 0."
# Raise exception if b is zero
if b == 0:
raise ZeroDivisionError("Division by zero is not allowed.")
# Perform the division
c=a/b
return c
def main():
try:
a = float(input("Enter value for a: "))
b = float(input("Enter value for b: "))
result = DivExp(a, b)
print(f"Result of a / b is: {result}")
except AssertionError as ae:
print(f"Assertion Error: {ae}")
except ZeroDivisionError as zde:

Dept. of AI&DS,AIT,Tumkur Page 19


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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

Outcome: Students will be able to use assertions, handle exceptions, and


implement user-defined functions in Python.

Dept. of AI&DS,AIT,Tumkur Page 20


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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.

Objective: To develop a Python program that defines a Complex class and


implements a function to add two complex numbers, and compute the sum of N
(N ≥ 2) 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}: "))

Dept. of AI&DS,AIT,Tumkur Page 21


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

num = Complex(real, imag)


total = [Link](num)
print("Sum is: ", end="")
[Link]()
Output:
How many complex numbers? (N >= 2): 3
Enter real and imaginary parts:
Real part of number 1: 2
Imag part of number 1: 5
Real part of number 2: 4
Imag part of number 2: 3
Real part of number 3: 1
Imag part of number 3: 5
Sum is: 7.0 + 13.0i

Outcome: Students will be able to implement classes, create objects, and perform
operations on user-defined data types in Python.

Dept. of AI&DS,AIT,Tumkur Page 22


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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

Dept. of AI&DS,AIT,Tumkur Page 23


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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)

Output: Enter a paragraph:


how are you brother
Number of sentences: 1
Number of words: 4
Longest word: brother
Word Frequencies:
how: 1
are: 1
you: 1
brother: 1

Outcome: Students will be able to apply string manipulation, dictionaries, and


basic text analysis concepts in Python.

Dept. of AI&DS,AIT,Tumkur Page 24


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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

Dept. of AI&DS,AIT,Tumkur Page 25


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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

Dept. of AI&DS,AIT,Tumkur Page 26


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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.

Dept. of AI&DS,AIT,Tumkur Page 27


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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

Dept. of AI&DS,AIT,Tumkur Page 28


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

print(f"Average marks: {average:.2f}")


print(f"Topper: {topper[0]} with marks {topper[1]}")

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.

Dept. of AI&DS,AIT,Tumkur Page 29


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

12) Develop a program to display contents of a folder recursively (Directory)


having sub-folders and files (name and type).
Objective: To develop a Python program that displays the contents of a directory
recursively, including files and sub-folders with their names and types.
import os
def list_directory(path, indent=0):
try:
items = [Link](path)
except PermissionError:
print(' ' * indent + "[Permission Denied]")
return
for item in items:
full_path = [Link](path, item)
if [Link](full_path):
print(' ' * indent + f"📁 {item}/")
list_directory(full_path, indent + 1)
else:
print(' ' * indent + f"📁 {item}")
if __name__ == "__main__":
folder = input("Enter folder path: ")
printf(f”\nContents of ‘{folder}’:\n”)
list_directory(folder)

Output:
Enter folder path: D:\CSE\CSE\Example

Dept. of AI&DS,AIT,Tumkur Page 30


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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.

Dept. of AI&DS,AIT,Tumkur Page 31


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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.

Dept. of AI&DS,AIT,Tumkur Page 32


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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.

Dept. of AI&DS,AIT,Tumkur Page 33


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

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

Dept. of AI&DS,AIT,Tumkur Page 34


PYTHON PROGRAMMING(1BPLC105B/1BPLC205B)

30. What is recursion?


Answer: Recursion is a function calling itself repeatedly to solve a problem
31. What is a string in Python?
Answer: A string is a sequence of characters enclosed in single or double quotes.
Example: "Hello" or 'Python'.
32. What does the strip() method do?
Answer: The strip() method removes leading and trailing spaces from a string.
Example:
[Link]()
33. What does the sort() method do?
Answer: The sort() method arranges the elements of a list in ascending order.
Example:
[Link]()
34. What is recursion in directory traversal?
Answer: Recursion means a function calling itself to process subfolders and files inside a
directory.
35. What is CSV file?
Answer: CSV (Comma Separated Values) is a file format used to store tabular data where values
are separated by commas.

Dept. of AI&DS,AIT,Tumkur Page 35

You might also like