Python Laboratory Manual
Python Laboratory Manual
INSTITUTION VISION
To impact quality technical education with a focus on Research and Innovation emphasizing on
Development of Sustainable and Inclusive Technology for the benefit of society.
INSTITUTION MISSION
To provide an environment that enhances creativity and Innovation in pursuit of Excellence.
To nurture teamwork in order to transform individuals as responsible leaders and entrepreneurs.
To train the students to the changing technical scenario and make them to understand the importance
of Sustainable and Inclusive technologies.
DEPARTMENT VISION
Computer Science and Design Engineering Department shall architect the most innovative programs to
deliver competitive and sustainable solutions using cutting edge technologies and implementations, for
betterment of society and research.
DEPARTMENT MISSION
To adopt the latest industry trends in teaching learning process in order to make students competitive in
the job market
To encourage forums that enable students to develop skills in multidisciplinary areas and emerging
technologies
To encourage research and innovation among students by creating an environment of learning through
active participation and presentations
To collaborate with industry and professional bodies for the students to gauge the market trends and
train accordingly.
To create an environment which fosters ethics and human values to make students responsible citizens.
COURSE INFORMATION SHEET
REVISED BLOOM’S
Sl. No. DESCRIPTION TAXONOMY
(RBT)LEVEL
Prerequisite
Students should be familiarized about Python installation and setting Python environment
Usage of IDLE or IDE like PyCharm should be introduced
Python Installation: https://www.youtube.com/watch?v=Kn1HF3oD19c
PyCharm Installation: https://www.youtube.com/watch?v=SZUNUB6nz3g
PO PSO
CO 1 2 3 4 5 6 7 8 9 10 11 12 1 2 3
CO1 3 - - 2 - 1 - - 2 - 1 2 - 2 1
CO2 2 - - 1 2 - - - 3 2 - 2 - 2 1
CO3 2 2 - 1 - 1 - - 1 2 - 2 - 2 1
CO4 3 - - 2 - - - - 2 2 - 2 - 2 1
CO5 2 3 - 2 - 2 - - 2 2 - 2 - 2 1
TEXTBOOKS:
1. Al Sweigart, “Automate the Boring Stuff with Python”,1stEdition, No Starch Press,
2015. (Available under CC-BY-NC-SA license at https://automatetheboringstuff.com/)
2. Reema Thareja “Python Programming Using Problem Solving Approach” Oxford
University Press.
3. 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)
LISTS OF EXPERIMENTS
Course
Sl. No. Name of the Experiment
Outcome(CO’s)
Aim: Introduce the Python fundamentals, data types, operators, flow
control and exception handling in Python.
a) Write a Python program that accepts an integer from the user and
1 determines whether it is a prime number or not. CO1
b) Write a Python program that reads a list of numbers from the user
and calculates the sum of all even numbers in the list.
Aim: Demonstrating creation of functions, passing parameters and
return values.
a) Write a Python program that defines a function
calculate_Fibonacci which accepts a positive integer n as input.
The function calculates the Fibonacci number at position n using
2 the formula Fn = Fn-1 + Fn-2, where F0 = 0 and F1 = 1. The CO2
program should display the Fibonacci number at position n or a
suitable error message if the input value is not a positive integer.
SOFTWARE REQUIREMENTS:
Python 3.11.3, IDLE editor
HARDWARE REQUIREMENTS:
PC – Intel / AMD Core i2 or above, 2 GB RAM, 500 GB Hard disk.
Step-2:Go to Downloads and download the latest version of python for windows, here latest version is
Python 3.11.3
PROGRAM -1
(A). Write a Python program to check whether a given number is prime or not.
def is_prime(number):
if number < 2:
return False
return True
OUTPUT
PROGRAM -1
(B). Write a Python program to get a list of numbers and calculate sum of all even numbers.
OUTPUT
PROGRAM -2
(A). Write a Python program in which each new term in the Fibonacci sequence is generated by
adding the previous two terms.
def recur_fibo(n):
if n <= 1:
return n
else:
return(recur_fibo(n-1) + recur_fibo(n-2))
# take input from the user
nterms = int(input("enter the number of terms: "))
# check if the number of terms is valid
if nterms <= 0:
print("Plese enter a positive integer")
else:
print("Fibonacci sequence:")
for i in range(nterms):
print(recur_fibo(i))
OUTPUT
PROGRAM -2
(B). Write a Python program to get maximum number from the given list of numbers.
def find_maximum(numbers):
if not numbers:
raise ValueError("The list is empty.")
maximum = numbers[0] # Initialize maximum with the first element
for num in numbers:
if num > maximum:
maximum = num
return maximum
# Call the function with a list of numbers and store the result in a variable
numbers = [1, 40, 2, 88, 3]
max_num = find_maximum(numbers)
# Print the result
print("The maximum number is:", max_num)
OUTPUT
PROGRAM -3
(A).Write a Python program that accepts a sentence from the user and counts the number of
occurrences of a specific word in the sentence. The program should prompt the user to enter
both the sentence and the word to search for.
return count
OUTPUT
PROGRAM -3
(B). Write a Python program that calculates the string similarity between two given strings
provided by the user. The program should prompt the user to enter both strings and then calculate
the similarity score between them.
return similarity
OUTPUT
PROGRAM -4
(A). Write a Python program that takes a list of numbers as input from the user and calculates the
sum of all the numbers in the list. The program should keep accepting numbers until the user enters
a negative number.
numbers = []
OUTPUT
PROGRAM -4
(B). Write a Python program that reads a sentence from the user and counts the frequency of each
word in the sentence. The program should store the word frequencies in a dictionary, where the
words are the keys and the frequencies are the values.
def count_word_frequencies(sentence):
# Convert the sentence to lowercase and split into words
words = sentence.lower().split()
return frequencies
OUTPUT
PROGRAM -5
(A). Write a Python program that takes a list of words as input from the user and filters out words
that start with a specific prefix. The program should prompt the user to enter the list of words and
the prefix to filter.
OUTPUT
PROGRAM -5
(B). Write a Python program that takes a sentence as input from the user and extracts all the email
addresses present in the sentence. The program should use regular expressions to identify and extract
the email addresses.
import re
def extract_email_addresses(sentence):
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b'
email_addresses = re.findall(pattern, sentence)
return email_addresses
OUTPUT
PROGRAM -6
(A). Write a Python program that reads the content of a text file named "input.txt" and counts
the number of occurrences of each word in the file. Then, write the word count results to a new
file named "output.txt" in the format "word: count" for each word found in the input file.
Ensure that the program ignores punctuation and treats uppercase and lowercase letters as the
same word.
import string
# Usage example
input_file = "input.txt"
output_file = "output.txt"
count_words(input_file, output_file)
OUTPUT
PROGRAM -6
(B). Create a Python program that takes a directory path as input from the user and lists all the files
and subdirectories within that directory. Additionally, the program should write the names of all the
files in a separate text file named "file_list.txt".
import os
def list_files_and_subdirectories(directory):
file_list = []
for root, directories, files in os.walk(directory):
for file in files:
file_list.append(os.path.join(root, file))
OUTPUT
PROGRAM -7
(A). Create a class called Rectangle with the following attributes and methods:
Attributes: length and width
Methods:
Area (): Calculate and return the area of the rectangle.
Perimeter (): Calculate and return the perimeter of the rectangle.
Create an object of the Rectangle class, initialize its attributes, and display its area and
perimeter.
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
OUTPUT
PROGRAM -7
(B). Create a base class called Animal with the following attributes and methods:
Attributes: name and age
Methods:
speak(): Display a message saying "The animal speaks."
Create a derived class called Dog that inherits from the Animal class. Add a new method to the
Dog class called bark(), which displays a message saying "The dog barks."
Create an object of the Dog class, initialize its attributes, and demonstrate both the speak() and
bark() methods.
class Animal:
def __init__(self, name, age):
self.name = name
self.age = age
def speak(self):
print("The animal speaks.")
class Dog(Animal):
def bark(self):
print("The dog barks.")
OUTPUT
PROGRAM -8
(A). Create a class called Shape with a method calculate_area(). The Shape class should be the base
class for three other classes: Rectangle, Triangle, and Circle. Each subclass should have its own
implementation of the calculate_area() method to calculate and return the area specific to that shape.
Demonstrate polymorphism by creating objects of each class and calling the calculate_area() method.
import math
class Shape:
def calculate_area(self):
pass
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def calculate_area(self):
return self.length * self.width
class Triangle(Shape):
def __init__(self, base, height):
self.base = base
self.height = height
def calculate_area(self):
return 0.5 * self.base * self.height
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def calculate_area(self):
return math.pi * self.radius ** 2
# Demonstrate polymorphism
shapes = [Rectangle(4, 5), Triangle(3, 6), Circle(2)]
for shape in shapes:
print("Area:", shape.calculate_area())
OUTPUT
PROGRAM -9
import pandas as pd
OUTPUT
PROGRAM -9
import requests
from bs4 import BeautifulSoup
OUTPUT