VISVESVARAYA TECHNOLOGICAL UNIVERSITY
JNANA SANGAMA, BELGAVI
590018 , KARNATAKA
Python Programming
(1BPLC105B) / Laboratory
MMannual Prepared by
D Dr. Swetha G, Associate Professor
Prof. Kruthi T C,Assistant Professor
DDepartment of Computer Science & Engineering
R.R. Institute of Technology
Academic Year 2025-26
-2
Department of Computer Science & Engineering
College Vision "To be a Premier globally recognized Institute with ensuring academic excellence, Innovation and
fostering Research in the field of Engineering"
College • To consistently strive for Academic Excellence
Mission • To promote collaborative Research & Innovation
• To create holistic teaching learning environment that build ethically sound manpower
who contribute to the stake holders operating at Global environment
Department To arise as an excellent learning center in the field of Computer Science & Engineering by fostering a
skilled, innovative professionals to build a strong nation.
Vision
Department • To provide a conceptual foundation that caters the career required to adopt for changing
Mission technology in computer science.
• To bridge the gap between academics and the latest tools, technologies in the area of
hardware and software.
• To set out co-curricular open doors for student’s participation in advancements and recent
trends.
• To explore the potential and excel the students towards research to attain Novelty.
Program PEO1: Proficient to recognize contemporary issues and provide solutions using broad knowledge
Educational
of computer science.
Objectives
(PEOs) PEO2: Ability to plan, analyze, design, evolve project implementing capabilities and skills in IT
industry.
PEO3: Drive to adapt new computing technologies lifelong to acquire professional greatness.
PEO4: Possess professional, ethical, social responsibilities, communicational skills and team
work needed for a successful professional carrier.
Program PSO1: Apply the software practices, principals to design and analyse the complex computer based system.
Specific PSO2: Design, implement and validate system software and application software to the various societal
Outcomes needs.
(PSOs)
Program Outcomes (POs)
PO1 Engineering Knowledge: Apply knowledge of mathematics and science, with fundamentals of
Computer Science & Engineering to be able to solve complex engineering problems related to CSE.
PO2 Problem Analysis: Identify, Formulate, review research literature and analyse complex
engineering problems related to CSE and reaching substantiated conclusions using first principles
of mathematics, natural sciences and engineering sciences.
PO3 Design/Development of Solutions: Design solutions for complex engineering problems related to
CSE 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 computer science related 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
CSE professional engineering practice.
PO7 Environment and Sustainability: Understand the impact of the CSE 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 able to comprehend and with 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 management principles and apply these to one’s own work, as a member and leader in
a team, to manage projects and in multi-disciplinary environments.
PO12 Life-Long Learning: Recognize the need for and have the preparation and ability to engage in
independent and life-long learning the broadest context of technological change.
Programming Exercises:
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 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
3a 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).
Python Programming
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).
Sample Output
Select Operation:
1. Add
2. Subtract
3. Multiply
4. Divide
Enter first number: 10
Enter second number: 5
Enter your choice (1-4): 3
The product of 10.0 and 5.0 is: 50.0
1|Page Dept of CSE ,RRIT
Python Programming
1b. Develop a program to read the name and year of birth of a person. Display whether the person is a
senior citizen or not. print("Select Operation:")
Sample Output
Enter your name: xyz
Enter your year of birth: 1958
Hello xyz!
Your age is: 67
You are a Senior Citizen.
2|Page Dept of CSE ,RRIT
Python Programming
2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
SAMPLE OUTPUT :
Input
How many terms? 6
Output
Fibonacci sequence: 0
1
1
2
3
5
3|Page Dept of CSE ,RRIT
Python Programming
2b. 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
4|Page Dept of CSE ,RRIT
Python Programming
SAMPLE OUTPUT :
List Operations Menu:
1. Insert an element
2. Remove an element
3. Append an element
4. Display the length of the list
5. Pop an element
6. Clear the list
7. Display the list
8. Exit
Enter your choice (1-8): 3
Enter element to append: apple
Updated List: ['apple']
Enter your choice (1-8): 1
Enter element to insert: mango
Enter position to insert at (0-based index): 0
Updated List: ['mango', 'apple']
5|Page Dept of CSE ,RRIT
Python Programming
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.
SAMPLE OUTPUT:
Enter the number of elements (N): 5
Enter the numbers:
Number 1: 10
Number 2: 12
Number 3: 23
Number 4: 23
Number 5: 16
--- Statistical Results ---
Numbers entered: [10.0, 12.0, 23.0, 23.0, 16.0]
Mean of the numbers: 16.80
Variance of the numbers: 28.16
Standard Deviation of the numbers: 5.30
6|Page Dept of CSE ,RRIT
Python Programming
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.
SAMPLE OUTPUT:
enter the number: 12365478456258
digit frequency
1 1
2 2
3 1
4 2
5 3
6 2
7 1
8 2
7|Page Dept of CSE ,RRIT
Python Programming
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.
How It Works:
1. Reads the file.
2. Converts all text to lowercase and splits into words.
3. Uses a dictionary to count how many times each word appears.
4. Sorts the dictionary by frequency.
5. Displays the top 10 most frequent words.
Example:
Input file (data.txt):
Python is fun and Python is easy. Python is powerful.
Output:
Top 10 most frequent words:
python : 3
is : 3
fun : 1
and : 1
easy. : 1
powerful. : 1
8|Page Dept of CSE ,RRIT
Python Programming
5a) 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].
sample output:
Enter marks for 6 subjects:
Enter mark 1: 75
Enter mark 2: 88
Enter mark 3: 62
Enter mark 4: 90
Enter mark 5: 80
Enter mark 6: 70
Marks from highest to lowest:
90
88
80
75
70
62
9|Page Dept of CSE ,RRIT
Python Programming
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()].
SAMPLE OUTPUT:
Input file (data.txt):
Banana
Apple
Mango
Orange
Grapes
Output file (sorted_data.txt):
Apple
Banana
Grapes
Mango
Orange
10 | P a g e Dept of CSE ,RRIT
Python Programming
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.
SAMPLE OUTPUT:
Case 1: Valid Input
Enter value for a: 10
Enter value for b: 2
Result of division (c = a / b): 5.0
Case 2: a <= 0
Enter value for a: -5
Enter value for b: 2
Error: a must be greater than 0
Case 3: b = 0
Enter value for a: 10
Enter value for b: 0
Error: Division by zero is not allowed
11 | P a g e Dept of CSE ,RRIT
Python Programming
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.
SAMPLE OUTPUT:
Enter how many complex numbers you want to add (N >= 2): 3
Enter Complex Number 1:
Enter real part: 2
Enter imaginary part: 3
Enter Complex Number 2:
Enter real part: 4
Enter imaginary part: 5
Enter Complex Number 3:
Enter real part: 1
Enter imaginary part: 2
The sum of all complex numbers is:
7.0 + 10.0i
12 | P a g e Dept of CSE ,RRIT
Python Programming
9) Text Analysis Tool: Build a tool that analyses a paragraph: frequency of each word, longest word,
number of sentences, etc
Sample Output
Input:
Enter a paragraph:
Python is simple. Python is powerful and easy to learn. I love Python!
Output:
--- Text Analysis Report ---
Number of sentences: 3
Number of words: 12
Longest word: powerful
Word Frequency:
python : 3
is : 2
simple : 1
powerful : 1
and : 1
easy : 1
to : 1
learn : 1
i:1
love : 1
13 | P a g e Dept of CSE ,RRIT
Python Programming
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.
Sample CSV (weather.csv):
Date,Temperature,Rainfall
2025-09-01,30,5
2025-09-02,32,0
2025-09-03,29,10
2025-09-04,31,2
Output:
Enter CSV filename: weather.csv
Available columns: ['Date', 'Temperature', 'Rainfall']
Enter the column name to analyze: Temperature
--- Summary Report ---
Maximum: 32.0
Minimum: 29.0
Average: 30.5
14 | P a g e Dept of CSE ,RRIT
Python Programming
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.)
SAMPLE OUTPUT:
Enter the number of students: 3
Enter details for Student 1:
Name: Alice
Marks: 85
Enter details for Student 2:
Name: Bob
Marks: 92
Enter details for Student 3:
Name: Charlie
Marks: 78
--- All Student Records ---
Name: Alice, Marks: 85.0
Name: Bob, Marks: 92.0
Name: Charlie, Marks: 78.0
--- Summary Report ---
Average Marks: 85.0
Topper: Bob with 92.0 marks
15 | P a g e Dept of CSE ,RRIT
Python Programming
12) Develop a program to display contents of a folder recursively (Directory) having sub-folders and files
(name and type).
Sample Output:
Enter the folder path: TestFolder
Contents of the folder:
File: file1.txt
File: file2.txt
Folder: SubFolder1
File: file3.txt
File: file4.txt
Folder: SubFolder2
File: file5.txt
16 | P a g e Dept of CSE ,RRIT
Python Programming
Sample programs in python:
1. Hello World
print("Hello, World!")
Output:
Hello, World!
2. Add Two Numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("Sum:", a + b)
Sample Input:
Enter first number: 5
Enter second number: 7
Output:
Sum: 12
3. Check Even or Odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
Sample Input:
Enter a number: 8
Output:
Even
4. Find Largest of Three Numbers
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
largest = max(a, b, c)
print("Largest number:", largest)
Sample Input:
Enter first number: 5
Enter second number: 10
Enter third number: 7
Output:
Largest number: 10
5. Simple Calculator
a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
print("Sum:", a+b)
print("Difference:", a-b)
print("Product:", a*b)
print("Quotient:", a/b)
Sample Input:
Enter first number: 10
Enter second number: 2
Output:
Sum: 12.0
Difference: 8.0
Product: 20.0
Quotient: 5.0
6. Factorial of a Number
17 | P a g e Dept of CSE ,RRIT
Python Programming
num = int(input("Enter a number: "))
fact = 1
for i in range(1, num+1):
fact *= i
print("Factorial:", fact)
Sample Input:
Enter a number: 5
Output:
Factorial: 120
7. Fibonacci Series
n = int(input("How many terms? "))
a, b = 0, 1
for _ in range(n):
print(a, end=" ")
a, b = b, a+b
Sample Input:
How many terms? 6
Output:
011235
8. Check Prime Number
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, num):
if num % i == 0:
print("Not Prime")
break
else:
print("Prime")
else:
print("Not Prime")
Sample Input:
Enter a number: 7
Output:
Prime
9. Reverse a String
s = input("Enter a string: ")
print("Reversed:", s[::-1])
Sample Input:
Enter a string: Python
Output:
Reversed: nohtyP
10. Count Vowels in String
s = input("Enter a string: ").lower()
vowels = "aeiou"
count = sum(1 for char in s if char in vowels)
print("Number of vowels:", count)
Sample Input:
Enter a string: Hello World
Output:
Number of vowels: 3
Viva questions:
1. What is Python?
18 | P a g e Dept of CSE ,RRIT
Python Programming
Python is a high-level, interpreted, general-purpose programming language known for its simplicity and readability.
2. Who developed Python and when?
Python was developed by Guido van Rossum and first released in 1991.
3. What are the key features of Python?
Easy to read and write
Interpreted
Dynamically typed
Object-oriented
Large standard library
4. What is PEP 8?
PEP 8 is the Python Enhancement Proposal that provides coding style guidelines for Python.
5. How is Python interpreted?
Python code is executed line by line using the Python interpreter, which translates Python code into bytecode.
6. What are Python variables?
Variables are used to store data values in Python. You don’t need to declare their type explicitly.
7. How do you create a variable in Python?
x = 10
name = "Alice"
8. What are Python data types?
Common data types: int, float, str, bool, list, tuple, set, dict.
9. What is a list in Python?
A list is an ordered, mutable collection of elements.
my_list = [1, 2, 3]
10. What is a tuple?
A tuple is an ordered, immutable collection of elements.
my_tuple = (1, 2, 3)
11. Difference between list and tuple?
List: mutable, slower
Tuple: immutable, faster
12. What is a dictionary?
A dictionary stores key-value pairs.
my_dict = {"name": "Alice", "age": 20}
13. What is a set in Python?
A set is an unordered collection of unique elements.
my_set = {1, 2, 3}
14. What are Python operators?
Operators are symbols that perform operations on variables. Examples: +, -, *, /, %, **, //.
15. What is the difference between / and //?
/ returns a float division result
// returns an integer division result
16. What is a function in Python?
A function is a block of reusable code that performs a specific task.
17. How do you define a function in Python?
def add(a, b):
return a + b
18. What are Python loops?
Loops are used to execute a block of code multiple times. Types: for and while.
19. Difference between for and while loop?
for: Iterates over a sequence
while: Runs until a condition is false
20. What is an if-else statement?
It allows conditional execution of code blocks.
21. How do you write an if-else statement?
if x > 0:
print("Positive")
else:
print("Non-positive")
19 | P a g e Dept of CSE ,RRIT
Python Programming
22. What is indentation in Python?
Indentation is used to define blocks of code; Python does not use braces {}.
23. What are Python strings?
Strings are sequences of characters enclosed in quotes.
s = "Hello"
24. How do you access characters in a string?
By indexing: s[0] gives 'H'.
25. What is slicing?
Slicing extracts a part of a string or list:
s[0:3] # 'Hel'
26. What is the difference between mutable and immutable objects?
Mutable: Can be changed (list, dict, set)
Immutable: Cannot be changed (tuple, str, int, float)
27. What is Python’s None?
None represents the absence of a value or a null value.
28. What is Python’s pass statement?
pass is a null statement; it does nothing. Useful as a placeholder.
29. What is a Python module?
A module is a file containing Python code (functions, classes, variables) that can be imported.
30. How do you import a module?
import math
31. What is Python’s import statement?
It allows you to use functions, classes, and variables from another module.
32. What is Python’s dir() function?
dir() lists all the attributes and methods of an object.
33. What are Python comments?
Comments are lines ignored by the interpreter. Single-line: # comment, multi-line: ''' comment '''.
34. Difference between == and is?
== checks value equality
is checks object identity (same memory location)
35. What is Python’s len() function?
len() returns the length of an object (string, list, tuple, etc.)
36. What is Python’s type() function?
type() returns the type of an object.
37. What are Python boolean values?
Boolean values are True or False.
38. What is a Python list comprehension?
A concise way to create lists:
squares = [x*x for x in range(5)]
39. What is Python’s range() function?
range() generates a sequence of numbers.
for i in range(5): # 0 to 4
print(i)
40. What are Python exceptions?
Exceptions are runtime errors that can be handled using try-except.
41. How do you handle exceptions?
try:
x = 1/0
except ZeroDivisionError:
print("Cannot divide by zero")
42. What is Python’s finally block?
finally executes code no matter what, used for cleanup.
43. What are Python classes and objects?
Class: blueprint of an object
Object: instance of a class
20 | P a g e Dept of CSE ,RRIT
Python Programming
44. How do you define a class?
class Student:
def __init__(self, name):
self.name = name
45. What is __init__ in Python?
__init__ is a constructor method called when an object is created.
46. What is inheritance in Python?
Inheritance allows one class to inherit properties and methods from another class.
47. What is Python’s self?
self refers to the instance of the class and is used to access attributes/methods.
48. Difference between shallow copy and deep copy?
Shallow copy: copies the reference (changes affect original)
Deep copy: copies the object fully (independent copy)
49. What is Python’s with statement?
with simplifies file handling and ensures proper closure:
with open("file.txt") as f:
data = f.read()
50. What are Python built-in functions?
Functions provided by Python, e.g., print(), len(), sum(), max(), min(), type().
21 | P a g e Dept of CSE ,RRIT