Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
55 views

Python Lab Manual 21EC643

Uploaded by

ndtalekar156
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views

Python Lab Manual 21EC643

Uploaded by

ndtalekar156
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 41

GOVERNMENT OF KARNATAKA Form No:

Department of Collegiate and Technical Education Revision:


GOVERNMENT ENGINEERING COLLEGE, KARWAR - 581345
Department of Electronics & Communication Engineering
E-Mail: - principalgeckarwar@gmail.com Phone: 08382-285332 Date:

Visvesvaraya Technological University, Belagavi

Department of Electronics and Communication Engineering

Government Engineering College


Karwar Majali-581345

Python Programming [21EC643]


Laboratory Manual
for

VI SEM B.E. [E&C]

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.

Continuous Internal Evaluation:


Three Unit Tests each of 20 Marks (duration 01 hour)
1. First test at the end of 5th week of the semester
2. Second test at the end of the 10th week of the semester
3. Third test at the end of the 15th week of the semester

Two assignments each of 10 Marks


4. First assignment at the end of 4th week of the semester
5. Second assignment at the end of 9th week of the semester
Group discussion/Seminar/quiz any one of three suitably planned to attain the COs and POs for 20
Marks (duration 01 hours)
6. At the end of the 13th week of the semester
The sum of three tests, two assignments, and quiz/seminar/group discussion will be out of 100 marks and will be
scaled down to 50 marks (to have less stressed CIE, the portion of the syllabus should not be common
/repeated for any of the methods of the CIE. Each method of CIE should have a different syllabus portion of the
course).
CIE methods /question paper is designed to attain the different levels of Bloom’s taxonomy as per the
outcome defined for the course.
Semester End Examination:
Theory SEE will be conducted by University as per the scheduled timetable, with common question papers
for the subject (duration 03 hours)
1. The question paper will have ten questions. Each question is set for 20 marks.
2. There will be 2 questions from each module. Each of the two questions under a module (with a
maximum of 3 sub-questions), should have a mix of topics under that module.
The students have to answer 5 full questions, selecting one full question from each module. Marks scored out of
100 shall be reduced proportionally to 50 marks
Suggested Learning Resources:
Text Books:
1. Al Sweigart, “Automate the Boring Stuff with Python”,1 st Edition, No Starch Press, 2015. (Available
under CC-BY-NC-SA license at https://automatetheboringstuff.com/) (Chapters 1 to 8)
2. Allen B Downey, “Think Python: How to Think Like a Computer Scientist”, 2nd Edition, Green Tea
Press, 2015. (Available under CC-BY-NC license at
http://greenteapress.com/thinkpython2/thinkpython2.pdf) (Chapters 15 - 18)
(Download pdf/html files from the above links)
3. Charles R. Severance, “Python for Everybody: Exploring Data Using Python 3”, 1st, Create Space
Independent Publishing Platform, 2016
Web links and Video Lectures (e-Resources)
 https://www.youtube.com/watch?v=_xQNeOTRyig
 https://www.youtube.com/watch?v=kqtD5dpn9C8
Activity Based Learning (Suggested Activities in Class)/ Practical Based learning
 Write a program to generate Fibonacci series
 Write a program to find factorial of a number using function.
 Write a menu driven program to implement stack using Lists
 Create 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%
 Write a program to implement search and replace multiple occurrences of a given substring in the
main string in a list.
 Write a function called most_frequent that takes a string and prints the letters in decreasing order of
frequency.
 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.
 Write 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.

 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

1. Write a program to generate Fibonacci series


2. Write a program to find factorial of a number using function.

3. Write a menu driven program to implement stack using Lists.

4. Create 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%.

5. Write a program to implement search and replace multiple occurrences of a


given substring in the main string in a list.

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.

8. Write 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.

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.

Step 5: Inside the loop:

 Append the current value of a to the fib_series list.

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

 Increment count by 1 to keep track of the number of terms generated.

 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

while count < n:

fib_series.append(a)

a, b = b, a + b
count += 1

return fib_series

#Input

num_terms = int(input("Enter the number of terms for Fibonacci series: "))

if num_terms <= 0:

print("Please enter a positive integer.")

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.

Step 2: Check if n is equal to 0:

 If true, return 1 (This is because the factorial of 0 is defined as 1).

Step 3: If n is not equal to 0:

 Return n multiplied by the result of calling factorial(n-1).

Step 4: Repeat steps 2 and 3 recursively until n reaches 0.

Python Code:
def factorial(n):

if n == 0:

return 1

else:

return n * factorial(n-1)

# Input:

num = int(input("Enter a non-negative integer to find its factorial: "))

if num < 0:

print("Factorial is not defined for negative numbers.")

else:

print("Factorial of", num, "is", factorial(num))


Result:

Thus, a program to find factorial of a number using function were performed and the result is
verified using Python.
Experiment No. : 3

WRITE A MENU DRIVEN PROGRAM TO


IMPLEMENT STACK USING LISTS
Aim: To perform a menu driven program to implement stack using Lists in Python.

Algorithm:
Step 1: Initialization: Initialize an empty stack.

Step 2: Menu Loop:

 Enter a loop to repeatedly display a menu of stack operations and prompt the
user to choose an option.

 Based on the user's choice:

o Call the appropriate function (push(), pop(), peek(), display()), passing


the stack as an argument.

o Repeat until the user chooses to exit the program.

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 -

 Check if the stack is empty by checking its length (len(stack)).

 If the stack is not empty:


o Remove and return the last item from the stack using the pop() method
of lists.

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 -

 Check if the stack is empty by checking its length (len(stack)).

 If the stack is not empty:

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 -

 Check if the stack is empty by checking its length (len(stack)).

 If the stack is not empty:

o Print all the elements of the stack.

 If the stack is empty, print a message indicating that the stack is empty.
Python Code:
# Function to push element into the stack

def push(stack, item):

stack.append(item)

print("Pushed", item, "into the stack")

# Function to pop element from the stack

def pop(stack):

if len(stack) == 0:

print("Stack is empty. Cannot pop.")

else:

item = stack.pop()

print("Popped", item, "from the stack")

# Function to peek at the top element of the stack

def peek(stack):

if len(stack) == 0:

print("Stack is empty. Cannot peek.")

else:

print("Top element of the stack is:", stack[-1])

# Function to display the stack

def display(stack):

if len(stack) == 0:

print("Stack is empty.")

else:

print("Stack contents:", stack)


# Main function

def main():

stack = []

while True:

print("\nStack Operations:")

print("1. Push")

print("2. Pop")

print("3. Peek")

print("4. Display")

print("5. Exit")

choice = input("Enter your choice: ")

if choice == '1':

item = input("Enter element to push: ")

push(stack, item)

elif choice == '2':

pop(stack)

elif choice == '3':

peek(stack)

elif choice == '4':

display(stack)

elif choice == '5':

print("Exiting program.")

break

else:

print("Invalid choice. Please enter a valid option.")


if __name__ == "__main__":

main()

Result:

Thus, a menu driven program to implement stack using Lists were performed and the
result is verified using Python.
Experiment No. : 4

CREATE A DB USING DICTIONARIES CONTAINING


KEY AS USN AND RELATED FIELDS CONTAINING
NAME, GENDER, MARKS1, MARKS2 & MARKS3 OF
STUDENTS
Aim: To create 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% in Python.

Algorithm:
Step 1: Initialization Method (__init__()): Create an empty dictionary to store student
information.

Step 2: add_student() Method:

 Take student details as input (USN, Name, Gender, Marks1, Marks2, Marks3).

 Add the student details to the dictionary with USN as the key.

Step 3: update_student() Method:

 Take USN, field name, and new value as input.

 Find the student with the given USN.

 Update the specified field with the new value.

Step 4: search_student() Method:

 Take USN as input.

 Find the student with the given USN.

 Display the student's details if found.


Step 5: delete_student() Method:

 Take name as input.

 Find the student(s) with the given name.

 Delete the student(s) from the database.

Step 6: generate_report() Method:

 Calculate the average marks for each student.

 Print the details of students whose average marks are more than 70%.

Python Code:
class StudentDB:

def __init__(self):

self.students = {}

def add_student(self, usn, name, gender, marks1, marks2, marks3):

self.students[usn] = {'Name': name, 'Gender': gender, 'Marks1': marks1, 'Marks2':


marks2, 'Marks3': marks3}

def update_student(self, usn, field, new_value):

if usn in self.students:

if field in self.students[usn]:

self.students[usn][field] = new_value

print(f"Updated {field} for USN {usn} to {new_value}")

else:

print(f"{field} is not a valid field")

else:

print(f"USN {usn} not found")


def search_student(self, usn):

if usn in self.students:

print("Student Details:")

for key, value in self.students[usn].items():

print(f"{key}: {value}")

else:

print(f"USN {usn} not found")

def delete_student(self, name):

found = False

for usn, student in list(self.students.items()):

if student['Name'] == name:

del self.students[usn]

found = True

if found:

print(f"Deleted student with name: {name}")

else:

print(f"Student with name {name} not found")

def generate_report(self):

print("Students with average marks more than 70%:")

for usn, student in self.students.items():

avg_marks = (student['Marks1'] + student['Marks2'] + student['Marks3']) / 3

if avg_marks > 70:

print(f"USN: {usn}, Name: {student['Name']}, Average Marks: {avg_marks:.2f}")


# Input:

db = StudentDB()

db.add_student('1', 'John', 'Male', 80, 75, 90)

db.add_student('2', 'Alice', 'Female', 70, 65, 75)

db.add_student('3', 'Bob', 'Male', 85, 80, 95)

db.update_student('1', 'Name', 'Johnny')

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.

Step 3: Replace Operation: For each string in the 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):

# Iterate through each string in the list

for i, string in enumerate(string_list):

# Replace all occurrences of search_str with replace_str in the current string

string_list[i] = string.replace(search_str, replace_str)

# Input:

string_list = ["apple", "banana", "apple pie", "apple juice"]

search_str = "apple"

replace_str = "orange"
print("Original list of strings:", string_list)

search_replace_list_strings(string_list, search_str, replace_str)

print("After replacing all occurrences of 'apple' with 'orange':", 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

WRITE A FUNCTION CALLED MOST_FREQUENT


THAT TAKES A STRING AND PRINTS THE LETTERS
IN DECREASING ORDER OF FREQUENCY
Aim: To perform a function called most_frequent that takes a string and prints the letters in
decreasing order of frequency.

Algorithm:
Step 1: Input Parameter: The function takes a string string as input.

Step 2: Frequency Dictionary Creation:

Step 3: Create an empty dictionary called freq_dict to store the frequencies of each letter.

Step 4: Counting Letter Frequencies:

 Iterate through each character in the string.

 Check if the character is a letter using char.isalpha().

 If it's a letter, convert it to lowercase for case insensitivity.

 Update the frequency count for the letter in the freq_dict.

Step 5: Sorting Frequencies:

 Sort the freq_dict dictionary by values (frequencies) in descending order.

 Use the sorted() function with a custom key function to sort by frequency.

Step 6: Printing Letters in Decreasing Order of Frequency:

 Iterate through the sorted frequency dictionary.

 Print each letter along with its frequency.

Python Code:
def most_frequent(string):

# Create a dictionary to store letter frequencies

freq_dict = {}
# Count the frequency of each letter in the string

for char in string:

if char.isalpha(): # Check if the character is a letter

char = char.lower() # Convert to lowercase for case insensitivity

freq_dict[char] = freq_dict.get(char, 0) + 1

# Sort the dictionary by values (frequencies) in descending order

sorted_freq = sorted(freq_dict.items(), key=lambda x: x[1], reverse=True)

# Print the letters in decreasing order of frequency

for char, freq in sorted_freq:

print(f"{char}: {freq}")

# Input:

input_string = "Hello World"

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

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
Aim: To perform 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.

Algorithm:
Step 1: Import Required Libraries:

 Import the Counter class from the collections module.

 Import the re module for regular expressions.

Step 2: read_file(filename) Function:

 Open the file specified by filename in read mode.

 Read the contents of the file and return it as a string.

Step 3: build_histogram(text) Function:

 Use a regular expression (re.findall()) to extract words from the input text.

 Convert all words to lowercase to ensure case insensitivity.

 Build a histogram of word occurrences using the Counter class.

Step 4: print_most_common_words(histogram, n=5) Function:

 Get the n most common words along with their occurrences from the histogram.

 Print each word along with its count.

Python Code:
from collections import Counter

import re
def read_file(filename):

with open(filename, 'r') as file:

return file.read()

def build_histogram(text):

words = re.findall(r'\b\w+\b', text.lower()) # Extract words ignoring punctuation and case

return Counter(words)

def print_most_common_words(histogram, n=5):

most_common = histogram.most_common(n)

print("Most common words in the file:")

for word, count in most_common:

print(f"{word}: {count} occurrences")

# Input:

filename = 'sample.txt' # Replace 'sample.txt' with the path to your file

file_content = read_file(filename)

print("Contents of the file:")

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

WRITE 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
Aim: To perform 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.

Algorithm:
Step 1: Import Required Library:

 Import the os module to work with operating system functionalities.

Step 2: find_files_with_suffix(directory, suffix) Function:

 Define a function find_files_with_suffix that takes a directory path (directory) and


a suffix (suffix) as input.

 Initialize an empty list file_paths to store the complete paths of files with the
given suffix.

 Use os.walk() to recursively traverse the directory and its subdirectories.

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

 Return the list of file paths.

Python Code:
import os

def find_files_with_suffix(directory, suffix):

file_paths = []
for root, dirs, files in os.walk(directory):

for file in files:

if file.endswith(suffix):

file_paths.append(os.path.join(root, file))

return file_paths

# Input:

directory = '/path/to/directory' # Specify the directory to search

suffix = 'sample.txt' # Specify the suffix of the files to search for

file_paths = find_files_with_suffix(directory, suffix)

print("Files with suffix '{}' found in directory '{}' and its subdirectories:".format(suffix,
directory))

for file_path in file_paths:

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

WRITE PYTHON CODE TO EXTRACT FROM: AND


TO: EMAIL ADDRESSES FROM THE GIVEN TEXT
FILE USING REGULAR EXPRESSIONS
Aim: To perform a python code to extract From: and To: Email Addresses from the given
text file using regular expressions. https://www.py4e.com/code3/mbox.txt.

Algorithm:
Step 1: Import the re module: This module provides support for regular expressions in
Python.

Step 2: Define the extract_email_addresses_from_file() function:

 This function takes a file path (file_path) as input.

 It initializes empty lists from_addresses and to_addresses to store the extracted


email addresses.

 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 extracts "From:" email addresses using a regular expression pattern (r'From:\


s*([\w\.-]+@[\w\.-]+)') using re.findall(), which finds all matches of the pattern in
the text.

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

 Finally, it returns the from_addresses and to_addresses lists.

Python Code:
import re

def extract_email_addresses_from_file(file_path):

from_addresses = []

to_addresses = []
# Open the file and read its contents

with open(file_path, 'r') as file:

text = file.read()

# Extract From: email addresses using regular expression

from_matches = re.findall(r'From:\s*([\w\.-]+@[\w\.-]+)', text)

from_addresses.extend(from_matches)

# Extract To: email addresses using regular expression

to_matches = re.findall(r'To:\s*([\w\.-]+@[\w\.-]+)', text)

to_addresses.extend(to_matches)

return from_addresses, to_addresses

# Input:

file_path = 'sample.txt' # Replace 'sample.txt' with the path to your text file

from_addresses, to_addresses = extract_email_addresses_from_file(file_path)

print("From: Email Addresses:")

for address in from_addresses:

print(address)

print("\nTo: Email Addresses:")

for address in to_addresses:

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

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
Aim: To 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.

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 3: Define regular expression patterns:

 email_pattern is set to r'(\b[\w\.-]+@[\w\.-]+\b)'. This pattern matches an email


address in the given sentence. It uses the \b word boundary anchor to ensure that
the match is a complete word, followed by a sequence of word characters (\w),
dots (.), and hyphens (-), followed by the @ symbol, and then another sequence of
word characters, dots, and hyphens, ending with another word boundary anchor.

 time_pattern is set to r'(\d{2}:\d{2}:\d{2})'. This pattern matches the time of the


day in HH:MM:SS format. It uses \d{2} to match two digits for hours, followed
by a colon, two digits for minutes, another colon, and two digits for seconds.

Step 4: Extract email address and time of the day using regular expressions:

 re.search(email_pattern, sentence).group() is used to search for the first


occurrence of the email address pattern in the given sentence and extract it.

 re.search(time_pattern, sentence).group() is used to search for the first occurrence


of the time pattern in the given sentence and extract it.

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

sentence = "From rjlowe@iupui.edu Fri Jan 4 14:50:18 2008"

# Regular expression pattern to extract email address

email_pattern = r'(\b[\w\.-]+@[\w\.-]+\b)'

# Regular expression pattern to extract time of the day

time_pattern = r'(\d{2}:\d{2}:\d{2})'

# Extract email address using regular expression

email_address = re.search(email_pattern, sentence).group()

# Extract time of the day using regular expression

time_of_day = re.search(time_pattern, sentence).group()

# Print the extracted email address and time of the day

print("Email Address:", email_address)

print("Time of the Day:", time_of_day)

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

WRITE A PROGRAM TO READ, DISPLAY AND


COUNT NUMBER OF SENTENCES OF THE GIVEN
FILE
Aim: To write a program to read, display and count number of sentences of the given file.

Algorithm:
Step 1: Define the read_file() function:

 This function takes a file path (file_path) as input.

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

 If the file does not exist (raises a FileNotFoundError), it prints a message


indicating that the file was not found and returns None.

Step 2: Define the count_sentences() function:

 This function takes the text content (text) as input.

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

 It counts the number of non-empty sentences and returns the count.

Python Code:
def read_file(file_path):

try:

with open(file_path, 'r') as file:

return file.read()
except FileNotFoundError:

print(f"File '{file_path}' not found.")

return None

def count_sentences(text):

# Split the text into sentences based on common punctuation marks

sentences = text.split('. ') # Assumes sentences end with period and space

# Print and count each sentence

sentence_count = 0

for sentence in sentences:

if sentence: # Skip empty strings

print(sentence)

sentence_count += 1

return sentence_count

# Input:

file_path = 'sample.txt' # Replace 'sample.txt' with the path to your file

file_contents = read_file(file_path)

if file_contents:

print("\nNumber of sentences in the file:", count_sentences(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

WRITE A PROGRAM THAT GETS THE CURRENT


DATE AND PRINTS THE DAY OF THE WEEK
Aim: To write a program that gets the current date and prints the day of the week.

Algorithm:
Step 1: Import the datetime module: This module provides classes for manipulating dates and
times in Python.

Step 2: Define the print_day_of_week() function:

 This function does not take any input parameters.

 It gets the current date using datetime.datetime.now().date(), which returns a


datetime.date object representing the current date.

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

Step 3: Call the print_day_of_week() function:

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

# Get the current date

current_date = datetime.datetime.now().date()

# Get the day of the week (Monday = 0, Sunday = 6)

day_of_week = current_date.weekday()
# Define a list of weekday names

weekday_names = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday",


"Saturday", "Sunday"]

# Print the day of the week

print("Today is", weekday_names[day_of_week])

# Call the function to print the day of the week

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

WRITE A FUNCTION CALLED PRINT_TIME THAT


TAKES TWO TIME OBJECTS AND PRINTS TOTAL
TIME IT IN THE FORM HOUR:MINUTE:SECOND
Aim: To write a function called print_time that takes two Time objects and prints total time
it in the form hour:minute:second.

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.

Step 2: Define the print_time function:

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

def __init__(self, hour=0, minute=0, second=0):

self.hour = hour

self.minute = minute

self.second = second
def print_time(time1, time2):

# Calculate total seconds

total_seconds = (time1.hour + time2.hour) * 3600 + (time1.minute + time2.minute) * 60 +


time1.second + time2.second

# Calculate hours, minutes, and seconds

total_hours, remainder = divmod(total_seconds, 3600)

total_minutes, total_seconds = divmod(remainder, 60)

# Print the total time

print(f"Total time: {total_hours:02d}:{total_minutes:02d}:{total_seconds:02d}")

# Input:

time1 = Time(1, 30, 10)

time2 = Time(2, 45, 20)

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

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
Aim: To 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.

Algorithm:
Step 1: Import the datetime module: This module is used for working with dates and times in
Python.

Step 2: Define the get_birthday() function:

 This function prompts the user to enter their birthday in the format YYYY-MM-
DD.

 It continuously tries to parse the input as a date using datetime.strptime().

 If the input is successfully parsed, it returns the birthday as a datetime object.

 If the input is invalid (raises a ValueError), it prints an error message and


prompts the user to enter the birthday again.

Step 3: Define the calculate_age_and_time_until_next_birthday() function:

 This function calculates the user's age and the time until their next birthday.

 It compares the current date (datetime.today()) with the user's birthday to


determine their age.

 It calculates the year of the next birthday based on the current date and the user's
birthday.

 It creates a datetime object representing the next 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:

 This function is the entry point of the program.

 It calls get_birthday() to get the user's birthday.

 It calls calculate_age_and_time_until_next_birthday() to calculate the user's age


and the time until their next birthday.

 It prints the user's age and the time until their next birthday in days, hours,
minutes, and seconds.

Step 5: Execute the main() function:

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

birthday_str = input("Enter your birthday (YYYY-MM-DD): ")

birthday = datetime.strptime(birthday_str, "%Y-%m-%d")

return birthday

except ValueError:

print("Invalid date format. Please enter your birthday in YYYY-MM-DD format.")

def calculate_age_and_time_until_next_birthday(birthday):

today = datetime.today()

next_birthday_year = today.year if today.month < birthday.month or (today.month ==


birthday.month and today.day < birthday.day) else today.year + 1

next_birthday = datetime(next_birthday_year, birthday.month, birthday.day)


age = today.year - birthday.year if today >= birthday else today.year - birthday.year - 1

time_until_next_birthday = next_birthday - today

return age, time_until_next_birthday

def main():

birthday = get_birthday()

age, time_until_next_birthday = calculate_age_and_time_until_next_birthday(birthday)

print(f"Your age: {age} years")

print(f"Time until your next birthday: {time_until_next_birthday.days} days,


{time_until_next_birthday.seconds // 3600} hours, {time_until_next_birthday.seconds %
3600 // 60} minutes, {time_until_next_birthday.seconds % 60} seconds")

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.

You might also like