Python Lab Manual 21EC643
Python Lab Manual 21EC643
Lab In-Charge:
Prof. Sinchana G S and Dr. Choodarathnakara A L
VISVESVARAYA TECHNOLOGICAL UNIVERSITY, BELAGAVI
B.E: Electronics & Communication Engineering / B.E: Electronics & Telecommunication
Engineering NEP, Outcome Based Education (OBE) and Choice Based Credit System (CBCS)
(Effective from the academic year 2021 – 22)
VI Semester
Python Programming
Course Code 21EC643 CIE Marks 50
Teaching Hours/Week (L:T:P:S) 2:0:2:0 SEE Marks 50
Total Hours of Pedagogy 40 Total Marks 100
Credits 3 Exam Hours 3
Course objectives:
To learn programming using Python
Develop application using Python
Teaching-Learning Process (General Instructions)
The sample strategies, which the teacher can use to accelerate the attainment of the various course outcomes are
listed in the following:
1. In addition to the traditional lecture method, different types of innovative teaching methods may be
adopted so that the delivered lessons shall develop student’s theoretical and programming skills.
2. State the need for learning Programming with real-life examples.
3. Support and guide the students for self–study.
4. You will also be responsible for assigning homework, grading assignments and quizzes, and
documenting students’ progress
5. Encourage the students for group learning to improve their creative and analytical skills.
6. Show short, related video lectures in the following ways:
As an introduction to new topics (pre-lecture activity).
As a revision of topics (post-lecture activity).
As additional examples (post-lecture activity).
As an additional material of challenging topics (pre-and post-lecture activity).
As a model solution of some exercises (post-lecture activity).
Module-1
Python Basics, Python language features, History , Entering Expressions into the Interactive Shell, The
Integer, Floating-Point, and String Data Types, String Concatenation and Replication, Storing Values in
Variables, Your First Program, Dissecting Your Program, Flow control, Boolean Values, Comparison
Operators, Boolean Operators, Mixing Boolean and Comparison Operators, Elements of Flow Control,
Program Execution, Flow Control Statements, Importing Modules, Ending a Program Early with sys.exit(),
Functions, def Statements with Parameters, Return Values and return Statements, The None Value, Keyword
Arguments and print(), Local and Global Scope, The global Statement, Exception Handling, A Short
Program: Guess the Number
Textbook 1: Chapters 1 – 3
Teaching-Learning Chalk and talk method, Simulation of modulation techniques
Process RBT Level: L1, L2, L3
Module-2
Data Structures: Lists: The List Data Type, Working with Lists Strings: Manipulating Strings, Working with
Strings, Useful String Methods Tuples and Dictionaries, basics Using Data Structures to Model Real-World
Things, Manipulating Strings.
Textbook 1: Chapters 4 – 6
Teaching-Learning Chalk and talk method/Power point presentation
Process RBT Level: L1, L2, L3
Module-3
Pattern Matching with Regular Expressions, Finding Patterns of Text Without Regular Expressions, Finding
Patterns of Text with Regular Expressions, More Pattern Matching with Regular Expressions, The find all ()
Method, Character Classes, Making Your Own Character Classes, The Caret and Dollar Sign Characters, The
Wildcard Character, Review of Regex Symbols.
Reading and Writing Files, Files and File Paths, The os.path Module, The File Reading/Writing Process,
Saving Variables with the shelve Module, Saving Variables with the p print. Format () Function Textbook 1:
Chapters 7, 8
Teaching-Learning Chalk and talk method / PowerPoint Presentation
Process RBT Level: L1, L2, L3
Module-4
Classes and objects: Programmer-defined types, Attributes, Rectangles, Instances as return values, Objects
are mutable, Copying, Classes and functions: Time, Pure functions, Modifiers, Prototyping versus planning,
Classes and methods: Object-oriented features, Printing objects, Another example, The init method, The str
method, Operator overloading, Type-based dispatch, Polymorphism.
Textbook 2: Textbook 2: Chapters 15 – 18
Teaching-Learning Chalk and talk method / PowerPoint Presentation
Process RBT Level: L1, L2, L3
Module-5
HTTP, The World’s simplest Web Browser, Retrieving an image over HTTP, Retrieving web pages with
urllib, Parsing html and scraping the web, Parsing HTML using RE, BeautifulSoup, Reading binary files
using urllib, XML, Parsing XML, Looping through nodes, JSON, Parsing JSON, API, geocoding Web
Service, Security & API usage, What is database?, Database Concepts, Database Browser, Creating a
database table, SQL, Spidering Twitter, Basic data modeling, Programming with multiple tables, Three kinds
of Keys, JOIN
Text book : Chapter 2, 13, 15
Teaching-Learning Chalk and talk method/Power point presentation
Process RBT Level: L1, L2, L3
Course outcomes (Course Skill Set)
At the end of the course the student will be able to:
1. To acquire programming skills in Python
2. To demonstrate data structure representation using Python
3. To develop the skill of pattern matching and files in Python
4. To acquire Object Oriented Skills in Python
5. To develop the ability to write database applications in Python
Assessment Details (both CIE and SEE)
The weightage of Continuous 5 End Examination) taken together.
Write python code to extract From: and To: Email Addresses from the given text file using regular
expressions. https://www.py4e.com/code3/mbox.txt.
Consider the sentence “From rjlowe@iupui.edu Fri Jan 4 14:50:18 2008”, Write python code to
extract email address and time of the day from the given sentence
Write a program to read, display and count number of sentences of the given file.
Write a program that gets the current date and prints the day of the week.
Write a function called print_time that takes two Time objects and prints total time it in the form
hour:minute:second.
Write a program that takes a birthday as input and prints the user’s age and the number of days, hours,
minutes and seconds until their next birthday.
List of Experiments
6. Write a function called most_frequent that takes a string and prints the letters
in decreasing order of frequency.
7. Write a program that reads a file, display the contents, builds a histogram of
the words in the file and print most common words in the file.
9. Write python code to extract From: and To: Email Addresses from the given
text file using regular expressions. https://www.py4e.com/code3/mbox.txt.
10. Consider the sentence “From rjlowe@iupui.edu Fri Jan 4 14:50:18 2008”,
Write python code to extract email address and time of the day from the given
sentence.
11. Write a program to read, display and count number of sentences of the given
file.
12. Write a program that gets the current date and prints the day of the week.
13. Write a function called print_time that takes two Time objects and prints total
time it in the form hour:minute:second.
14. Write a program that takes a birthday as input and prints the user’s age and
the number of days, hours, minutes and seconds until their next birthday.
Experiment No. : 1
WRITE A PROGRAM TO GENERATE FIBONACCI
SERIES
Aim: To perform a program to generate Fibonacci series using Python.
Algorithm:
Step 1: Initialize an empty list fib_series to store the Fibonacci series.
Step 2: Initialize variables a and b to 0 and 1 respectively, representing the first two numbers
in the Fibonacci sequence.
Step 3: Initialize a variable count to 0 to keep track of the number of terms generated.
Step 4: Enter a loop that continues until the count reaches n, the desired number of terms.
Update a to the value of b, and update b to the sum of the previous values of a
and b, effectively moving to the next Fibonacci number.
Once the loop completes, return the fib_series list containing the generated
Fibonacci series.
Python Code:
def fibonacci(n):
fib_series = []
a, b = 0, 1
count = 0
fib_series.append(a)
a, b = b, a + b
count += 1
return fib_series
#Input
if num_terms <= 0:
else:
print("Fibonacci series:")
print(fibonacci(num_terms))
Result:
Thus, the generation of Fibonacci series were performed and the result is verified using Python.
Experiment No. : 2
WRITE A PROGRAM TO FIND FACTORIAL OF A
NUMBER USING FUNCTION
Aim: To perform a program to find factorial of a number using function in Python.
Algorithm:
Step 1: Define a function factorial(n) that takes an integer n as input.
Python Code:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
# Input:
if num < 0:
else:
Thus, a program to find factorial of a number using function were performed and the result is
verified using Python.
Experiment No. : 3
Algorithm:
Step 1: Initialization: Initialize an empty stack.
Enter a loop to repeatedly display a menu of stack operations and prompt the
user to choose an option.
Push Function:
Step 1: Inputs:
The push() function takes two parameters: stack (a list representing the stack)
and item (the element to be pushed onto the stack).
Step 2: Operation:
Append the item to the stack using the append() method of lists.
Print a message confirming that the item has been pushed into the stack.
Pop Function:
Step 1: Inputs - The pop() function takes one parameter: stack (a list representing the
stack).
Step 2: Operation -
o Print a message indicating the item that has been popped from the
stack.
If the stack is empty, print a message indicating that the stack is empty and
cannot be popped.
Peek Function:
Step 1: Inputs - The peek() function takes one parameter: stack (a list representing the
stack).
Step 2: Operation -
o Print the last item of the stack (top element) without removing it.
If the stack is empty, print a message indicating that the stack is empty and
cannot be peeked.
Display Function:
Step 1: Inputs - The display() function takes one parameter: stack (a list representing the stack).
Step 2: Operation -
If the stack is empty, print a message indicating that the stack is empty.
Python Code:
# Function to push element into the stack
stack.append(item)
def pop(stack):
if len(stack) == 0:
else:
item = stack.pop()
def peek(stack):
if len(stack) == 0:
else:
def display(stack):
if len(stack) == 0:
print("Stack is empty.")
else:
def main():
stack = []
while True:
print("\nStack Operations:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
if choice == '1':
push(stack, item)
pop(stack)
peek(stack)
display(stack)
print("Exiting program.")
break
else:
main()
Result:
Thus, a menu driven program to implement stack using Lists were performed and the
result is verified using Python.
Experiment No. : 4
i) Update Name/gender/marks
iv) generate the report with avg marks more than 70% in Python.
Algorithm:
Step 1: Initialization Method (__init__()): Create an empty dictionary to store student
information.
Take student details as input (USN, Name, Gender, Marks1, Marks2, Marks3).
Add the student details to the dictionary with USN as the key.
Print the details of students whose average marks are more than 70%.
Python Code:
class StudentDB:
def __init__(self):
self.students = {}
if usn in self.students:
if field in self.students[usn]:
self.students[usn][field] = new_value
else:
else:
if usn in self.students:
print("Student Details:")
print(f"{key}: {value}")
else:
found = False
if student['Name'] == name:
del self.students[usn]
found = True
if found:
else:
def generate_report(self):
db = StudentDB()
db.search_student('1')
db.delete_student('Alice')
db.generate_report()
Result:
Thus, a DB using dictionaries containing key as USN and related fields containing Name,
gender, Marks1, Marks2 & Marks3 of students. Implement the following functions to perform
i) Update Name/gender/marks ii) search for usn and display the relevant fields iii) delete
based on search for name iv) generate the report with avg marks more than 70% was
performed and results are verified using python.
Experiment No. : 5
WRITE A PROGRAM TO IMPLEMENT SEARCH AND
REPLACE MULTIPLE OCCURRENCES OF A GIVEN
SUBSTRING IN THE MAIN STRING IN A LIST
Aim: To perform a program to implement search and replace multiple occurrences of a given
substring in the main string in a list.
Algorithm:
Step 1: Input Parameters: The function takes three input parameters: string_list, search_str,
and replace_str.
Step 2: Iteration through List: Iterate through each string in the string_list.
Use the replace() method to replace all occurrences of search_str with replace_str.
Step 4: Update List Element: Update the current string in the string_list with the modified
string obtained after replacement.
Python Code:
def search_replace_list_strings(string_list, search_str, replace_str):
# Input:
search_str = "apple"
replace_str = "orange"
print("Original list of strings:", string_list)
Result:
Thus, a program to implement search and replace multiple occurrences of a given substring in
the main string in a list was performed and the results are verified using python.
Experiment No. : 6
Algorithm:
Step 1: Input Parameter: The function takes a string string as input.
Step 3: Create an empty dictionary called freq_dict to store the frequencies of each letter.
Use the sorted() function with a custom key function to sort by frequency.
Python Code:
def most_frequent(string):
freq_dict = {}
# Count the frequency of each letter in the string
freq_dict[char] = freq_dict.get(char, 0) + 1
print(f"{char}: {freq}")
# Input:
most_frequent(input_string)
Result:
Thus, a function called most_frequent that takes a string and prints the letters in decreasing
order of frequency was performed and the results are verified using python.
Experiment No. : 7
Algorithm:
Step 1: Import Required Libraries:
Use a regular expression (re.findall()) to extract words from the input text.
Get the n most common words along with their occurrences from the histogram.
Python Code:
from collections import Counter
import re
def read_file(filename):
return file.read()
def build_histogram(text):
return Counter(words)
most_common = histogram.most_common(n)
# Input:
file_content = read_file(filename)
print(file_content)
histogram = build_histogram(file_content)
print("\nHistogram of words:")
print(histogram)
print_most_common_words(histogram)
Result:
Thus, a program that reads a file, display the contents, builds a histogram of the words in the
file and print most common words in the file was performed and the results are verified using
python.
Experiment No. : 8
Algorithm:
Step 1: Import Required Library:
Initialize an empty list file_paths to store the complete paths of files with the
given suffix.
For each file found in the directory tree, check if its filename ends with the
specified suffix.
If the file matches the suffix, append its complete path (obtained by joining the
root path and the filename) to the file_paths list.
Python Code:
import os
file_paths = []
for root, dirs, files in os.walk(directory):
if file.endswith(suffix):
file_paths.append(os.path.join(root, file))
return file_paths
# Input:
print("Files with suffix '{}' found in directory '{}' and its subdirectories:".format(suffix,
directory))
print(file_path)
Result:
Thus, a program that searches a directory and all of its subdirectories, recursively, and returns
a list of complete paths for all files with a given suffix was performed and the results are
verified using python.
Experiment No. : 9
Algorithm:
Step 1: Import the re module: This module provides support for regular expressions in
Python.
It opens the file specified by file_path in read mode ('r') using a context manager
(with statement) to ensure the file is properly closed after reading.
It reads the contents of the file using the read() method and stores it in the text
variable.
It extends the from_addresses list with the extracted "From:" email addresses.
It extracts "To:" email addresses using a similar regular expression pattern and
extends the to_addresses list with the extracted "To:" email addresses.
Python Code:
import re
def extract_email_addresses_from_file(file_path):
from_addresses = []
to_addresses = []
# Open the file and read its contents
text = file.read()
from_addresses.extend(from_matches)
to_addresses.extend(to_matches)
# Input:
file_path = 'sample.txt' # Replace 'sample.txt' with the path to your text file
print(address)
print(address)\
Result:
Thus, a code to extract From: and To: Email Addresses from the given text file using regular
expressions was performed and the results are verified using python.
Experiment No. : 10
Algorithm:
Step 1: Import the re module: This module provides support for regular expressions in
Python.
Step 2: Define the given sentence: The variable sentence contains the string "From
rjlowe@iupui.edu Fri Jan 4 14:50:18 2008", which represents the input sentence
from which email address and time of the day need to be extracted.
Step 4: Extract email address and time of the day using regular expressions:
Step 5: Print the extracted email address and time of the day: The extracted email address
and time of the day are printed to the console using print() statements.
Python Code:
import re
# Given sentence
email_pattern = r'(\b[\w\.-]+@[\w\.-]+\b)'
time_pattern = r'(\d{2}:\d{2}:\d{2})'
Result:
Thus, the sentence “From rjlowe@iupui.edu Fri Jan 4 14:50:18 2008” to extract email address
and time of the day from the given sentence was performed and results was verified using
python.
Experiment No. : 11
Algorithm:
Step 1: Define the read_file() function:
It attempts to open the file specified by file_path in read mode ('r') using a context
manager (with statement).
If the file exists, it reads its contents using the read() method and returns the
content as a string.
It splits the text into sentences based on the assumption that sentences end with a
period followed by a space ('. '), using the split('. ') method.
It iterates over each sentence and prints it, skipping any empty strings.
Python Code:
def read_file(file_path):
try:
return file.read()
except FileNotFoundError:
return None
def count_sentences(text):
sentences = text.split('. ') # Assumes sentences end with period and space
sentence_count = 0
print(sentence)
sentence_count += 1
return sentence_count
# Input:
file_contents = read_file(file_path)
if file_contents:
Result:
Thus, a program to read, display and count number of sentences of the given file was
performed and the results was verified using python.
Experiment No. : 12
Algorithm:
Step 1: Import the datetime module: This module provides classes for manipulating dates and
times in Python.
It uses the weekday() method on the datetime.date object to get the day of the
week as an integer (0 for Monday, 1 for Tuesday, ..., 6 for Sunday).
It defines a list weekday_names containing the names of the days of the week.
It prints the corresponding day of the week using the weekday_names list.
This line calls the print_day_of_week() function to execute the program and print
the current day of the week.
Python Code:
import datetime
def print_day_of_week():
current_date = datetime.datetime.now().date()
day_of_week = current_date.weekday()
# Define a list of weekday names
print_day_of_week()
Result:
Thus, a program that gets the current date and prints the day of the week was performed and
results was verified using python.
Experiment No. : 13
Algorithm:
Step 1: Define the Time class:
The Time class is defined to represent time with attributes hour, minute, and
second.
The __init__ method initializes these attributes with default values of 0 if not
provided.
This function takes two Time objects (time1 and time2) as input.
It calculates the total time in seconds by adding the hours, minutes, and seconds of
both time objects and converting them to seconds.
It then calculates the total hours, minutes, and seconds from the total seconds
using the divmod() function.
Finally, it prints the total time in the format hour:minute:second using formatted
strings (f"{total_hours:02d}:{total_minutes:02d}:{total_seconds:02d}").
Python Code:
class Time:
self.hour = hour
self.minute = minute
self.second = second
def print_time(time1, time2):
# Input:
print_time(time1, time2)
Result:
Thus, a function called print_time that takes two Time objects and prints total time it in the
form hour:minute:second was performed and results was verified using python.
Experiment No. : 14
Algorithm:
Step 1: Import the datetime module: This module is used for working with dates and times in
Python.
This function prompts the user to enter their birthday in the format YYYY-MM-
DD.
This function calculates the user's age and the time until their next birthday.
It calculates the year of the next birthday based on the current date and the user's
birthday.
It calculates the difference between the next birthday and the current date to get
the time until the next birthday.
It returns the age and the time until the next birthday.
Step 4: Define the main() function:
It prints the user's age and the time until their next birthday in days, hours,
minutes, and seconds.
This line ensures that the main() function is called when the script is executed,
running the program.
Python Code:
from datetime import datetime
def get_birthday():
while True:
try:
return birthday
except ValueError:
def calculate_age_and_time_until_next_birthday(birthday):
today = datetime.today()
def main():
birthday = get_birthday()
if __name__ == "__main__":
main()
Result:
Thus, a program that takes a birthday as input and prints the user’s age and the number of
days, hours, minutes and seconds until their next birthday was performed and results was
verified using python.