0% found this document useful (0 votes)
4 views41 pages

Python Lab Manual Dbatu Vivek

The document is a laboratory manual for Python programming at Shriram Institute of Engineering and Technology, detailing various experiments and their objectives, including calculating areas of shapes, finding unions and intersections of lists, and counting word frequencies. It includes guidelines for lab conduct, assessment criteria, and sample program codes for each experiment. The manual is structured to facilitate practical learning for students enrolled in the Computer Engineering department.

Uploaded by

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

Python Lab Manual Dbatu Vivek

The document is a laboratory manual for Python programming at Shriram Institute of Engineering and Technology, detailing various experiments and their objectives, including calculating areas of shapes, finding unions and intersections of lists, and counting word frequencies. It includes guidelines for lab conduct, assessment criteria, and sample program codes for each experiment. The manual is structured to facilitate practical learning for students enrolled in the Computer Engineering department.

Uploaded by

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

SHRIRAM INSTITUTE OF ENGINEERING AND TECHNOLOGY(POLY),PANIV-413113

[Affiliated to Dr. Babasaheb Ambedkar Technological University [ DBATU], Lonere]

Department of Computer Engineering

PYTHON PROGRAMMING
LABORATORY MANUAL

ACADEMIC YEAR 20 - 20 SEMESTER EVEN

NAME OF STUDENT

CLASS/ SEM./BATCH

ROLL NUMBER CSE -


SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

PYTHON PROGRAMMING
LABORATORY MANUAL

COURSE CLUSTER PROFESSIONAL CORE

COURSE CODE CREDIT BTCOL406

PRN. NO.

EXAM. NO.

MOBILE NO. (student) +91-

NAME OF FACULTY PROF. SHINDE V.S.


SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

LABORATORY CODE

1. Students should report to the concerned laboratory as per the time table.
2. Wash your hands before entering the computer lab.
3. Keep your bags in rack.
4. Remove your shoes and keep it in shoe stand.
5. Turn computer monitors off when asked by your teacher.
6. Do not go on banned websites.
7. No food or drinks near the keyboard.
8. Only use your assigned computer and workstation.
9. Do not change the settings on the computer.
10. Ask permission to download.
11. Ask permission to print documents
12. Save your work often.
13. If you are the last class of the day, please POWER DOWN all computers
and monitors.
SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

CERTIFICATE

This is certify that,

Miss/Mr.

Class Roll No. Batch has completed

all the Practical Work Satisfactorily/Unsatisfactorily in the

Computer Engineering Department of Subject; PYTHON

PROGRAMING

As prescribed by the DBATU UNIVERSITY, LONERE

in the Academic Year 20 - 20.

Date:

PROF V.S SHINDE

Subject In-Charge HOD Principal


SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

INDEX
Ex. Pg. Given Submission
Title of Experiment Marks Sign.
No. No. Date Date
Program to calculate area of
1 triangle, rectangle, circle 24 24

Program to find the union of two 24 24


2
lists
Program to find intersection of 24 24
3
two lists
Program to count the occurrences 24 24
4
of each word in a given string
sentence
Program to count the frequency 24 24
5
of words appearing in a string
using a dictionary
Program to find the length of a 24 24
6
list using recursion
Compute the diameter, 24 24
7
circumference and volume of a
sphere using class
Program to read a file and 24 24
8
capitalize the first letter of every
word in the file.
Program to remove the “i” th 24 24
9
occurrence of given word in a
list where words repeat
24 24
10. Program to create a dictionary
with key as first character and
value as words starting with
that character

Average Experiment Marks (out of 10)


SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering
PRACTICAL ASSESSMENT/ATTAINMENT (in-direct)

Performance Indicator Tools Marks Remark

Fundamental Knowledge

Analyze and Interpretation of Data

Constraint Design or Procedure

Identify/Formulate/Evaluate/Solution
of Problem

Lab. Ethics and Communication

Oral/Written/Graphical Form

Result and Measurement Error

Analysis and Theory Application

Accurate Documentation

Regular Attendance

Average Marks (out of 10)

U=Unsatisfactory (> 3) D= Developing (5-7) S= Satisfactory (8-10) E= Exemplary (10)


SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

Program to calculate area of triangle, rectangle,


EXPERIMENT NO. 01
Circle, square

GIVEN DATE

SUBMISSION DATE

SIGN. OF STUDENT

TOTAL
ATTENDANCE PRESENTATION UNDERSTANDING
MARKS

02 02 06 10

SIGN. OF FACULTY

REMARKS
EXPERIMENT NO. 01
1.1 AIM: -

Program to calculate area of triangle, rectangle, circle, and square.

1.2 THEORY:-

We will create a python program to calculate the areas of different shapes. We will
take user input for different parameters of different shapes to calculate shapes. We
will be using if-elif-else loop for the purpose of calculating. In this program, We will
ask the user to input the shape’s name. If it exists in our program then we will
proceed to find the entered shape’s area according to their respective formulas. If
that shape doesn’t exist then we will print “Sorry! We cannot find this shape.”
message on the screen.

1.3 PROGRAM CODE:-

# define a function for calculating


# the area of a shapes

def calculate_area(name):

# converting all characters


# into lower cases
name = name.lower()

# check for the conditions


if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))

# calculate area of rectangle


rect_area = l * b
print(f"The area of rectangle is{rect_area}.")
elif name == "square":
s = int(input("Enter square's side length: "))

# calculate area of square


sqt_area = s * s
print(f"The area of square is {sqt_area}.")

elif name == "triangle":


h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))

# calculate area of triangle


tri_area = 0.5 * b * h
print(f"The area of triangle is {tri_area}.")

elif name == "circle":


r = int(input("Enter circle's radius length: "))
pi = 3.14

# calculate area of circle


circ_area = pi * r * r
print(f"The area of circle is
{circ_area}.")

else:
print("Sorry! This shape is not available")

# driver code
if __name__ == "__main__" :

print("Calculate Shape Area")


shape_name = input("Enter the name of shape whose area you want to find: ")

# function calling
calculate_area(shape_name)
1.4 CONCLUSION:-

QUESTIONS:-

Q1) What is Python? List some popular applications of Python in the world of
technology.

Q2) What does the ‘#’ symbol do in Python?

Q3) Difference between for loop and while loop in Python


SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

EXPERIMENT NO. 02 Program to find union of two lists

GIVEN DATE

SUBMISSION DATE

SIGN. OF STUDENT

TOTAL
ATTENDANCE PRESENTATION UNDERSTANDING
MARKS

02 02 06 10

SIGN. OF FACULTY

REMARKS
EXPERIMENT NO. 02
2.1 AIM: -

Program to find union of two lists

2.2 PRE-REQUISITE:-

1. Knowledge of Union.
2. Knowledge of Lists in Python.

2.3 THEORY:-

Lists are used to store multiple items in a single variable. Lists are one of 4
built-in data types in Python used to store collections of data. List items are
indexed and you can access them by referring to the index number. Union of a
list means, we must take all the elements from list A and list B (there can be
more than two lists) and put them inside a single new list. There are various
orders in which we can combine the lists. For e.g., we can maintain the
repetition and order or remove the repeated elements in the final list and so
on. To get rid of all the repetitive elements from the initial list, we use the set()
function on both the lists, individually.

Then we add them using the “+” operator and pass as a new list.
2.4 Program:-

Program with Repetion of elements in list:


# Python program to illustrate union
# Maintained repetition
def Union(lst1, lst2):
final_list = lst1 + lst2
return final_list

# Driver Code
lst1 = [23, 15, 2, 14, 14, 16, 20 ,52]
lst2 = [2, 48, 15, 12, 26, 32, 47, 54]
print(Union(lst1, lst2))

Program with no repetition of elements:


# Python program to illustrate union
# Without repetition
def Union(lst1, lst2):
final_list = list(set(lst1) | set(lst2))
return final_list

# Driver Code
lst1 = [23, 15, 2, 14, 14, 16, 20 ,52]
lst2 = [2, 48, 15, 12, 26, 32, 47, 54]
print(Union(lst1, lst2))
2.5 CONCLUSION:-

QUESTION:

1. What’s a Python List Exactly?

2. When would you use a list vs dictionary?

3. What is python function?

4. What are arguments?


SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

Program to find intersection of two lists


EXPERIMENT NO. 03

GIVEN DATE

SUBMISSION DATE

SIGN. OF STUDENT

TOTAL
ATTENDANCE PRESENTATION UNDERSTANDING
MARKS

02 02 06 10

SIGN. OF FACULTY

REMARKS
EXPERIMENT NO. 03
3.1 AIM:

Program to find intersection of two lists.

3.2 Theory:-

A function is a block of code which only runs when it is called.


You can pass data, known as parameters, into a function. A function can return data as a
result. Intersection of two list means we need to take all those elements which are common
to both of the initial lists and store them into another list. Now there are various ways in
Python, through which we can perform the Intersection of the lists. This method includes
the use of set() method.

3.1 Program:-
Take user input for the following program:

Try for below lists:

Input :
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]
Output :
[9, 10, 4, 5]

Input :
lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
Output :
[9, 11, 26, 28]

# Python program to illustrate the intersection


# of two lists using set() method,

def intersection(lst1, lst2):


return list(set(lst1) & set(lst2))

# Driver Code
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]

print(intersection(lst1, lst2))
3.2 CONCLUSION:-

QUESTIONS:-

1. What is intersection?

2. What is the difference between list and tuples in Python?

3. What is name space in Python?


SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

EXPERIMENT NO. 04 Program to count the occurrences of each word in a


given string sentence.

GIVEN DATE

SUBMISSION DATE

SIGN. OF STUDENT

TOTAL
ATTENDANCE PRESENTATION UNDERSTANDING
MARKS

02 02 06 10

SIGN. OF FACULTY

REMARKS
EXPERIMENT NO. 04

4.1 AIM: -
Program to count the occurrences of each word in a given string sentence.

4.2 PRE-REQUISITE:-

1. Knowledge of String.

4.3 THEORY:-

Strings in python are surrounded by either single quotation marks, or double


quotation marks. This Python code defines a function named word_count that
takes a string (str) as an argument. The function counts the frequency of each word
in the input string and returns a dictionary where keys are unique words, and
values are the corresponding word frequencies.
4.4 PROGRAME CODE:-

# Define a function named word_count that takes one argument, 'str'.


def word_count(str):
# Create an empty dictionary named 'counts' to store word frequencies.
counts = dict()

# Split the input string 'str' into a list of words using spaces as separators store it in the
'words' list.
words = str.split()

# Iterate through each word in the 'words' list.


for word in words:
# Check if the word is already in the 'counts' dictionary.
if word in counts:
# If the word is already in the dictionary, increment its frequency by 1.
counts[word] += 1
else:
# If the word is not in the dictionary, add it to the dictionary with a frequency of 1.
counts[word] = 1

# Return the 'counts' dictionary, which contains word frequencies.


return counts

# Call the word_count function with an input sentence and print the results.
print( word_count('the quick brown fox jumps over the lazy dog.'))
4.5 CONCLUSION:-

QUESTIONS:-

Q1) Explain loops and conditional loops

Q2) List other data structures used in python?

Q3) What is Split()?


SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

Program to count the frequency of words appearing in a


EXPERIMENT NO. 05
string using a dictionary

GIVEN DATE

SUBMISSION DATE

SIGN. OF STUDENT

TOTAL
ATTENDANCE PRESENTATION UNDERSTANDING
MARKS

02 02 06 10

SIGN. OF FACULTY

REMARKS
EXPERIMENT NO. 05
5.1 AIM: -

Program to count the frequency of words appearing in a string using a dictionary

5.2 THEORY:-

The program uses a dictionary to efficiently count the frequency of each word.
In a dictionary, words serve as keys, and their frequencies serve as values.on
whitespace by default. It facilitates the processing of individual words in the
input string. The for loop iterates through each word in the list. The split()
method is crucial for breaking the input sentence into individual words.
Without splitting, the program would treat the entire sentence as a single
entity. The for loop iterates through each word in the list, allowing the program
to process words one by one and update their frequencies in the dictionary.
The if-else statement checks whether a word is already in the dictionary. If it is,
the count is incremented; if not, the word is added to the dictionary with a
count of 1. The final output is a dictionary containing words as keys and their
respective frequencies as values, providing a clear representation of the word
distribution in the input sentence.
5.3 PROGRAM CODE:-

def word_frequency_count(sentence):
# Initialize an empty dictionary to store word frequencies.
word_count = {}

# Split the input sentence into words.


words = sentence.split()

# Iterate through each word in the list of words.


for word in words:
# Check if the word is already in the dictionary.
if word in word_count:
# If present, increment the count by 1.
word_count[word] += 1
else:
# If not present, add the word to the dictionary with a count of 1.
word_count[word] = 1

return word_count

# Example usage:
input_sentence = "the quick brown fox jumps over the lazy dog"
result = word_frequency_count(input_sentence)
print(result)
5.4 CONCLUSION:-

QUESTIONS:-

Q1) Why is a dictionary chosen to store word frequencies??

Q2) Explain the purpose of the for loop in the code

Q3) What does the conditional if-else statement inside the loop check?

Q4) What would happen if you didn't split the sentence into words?.
SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

EXPERIMENT NO. 06 Program to find the length of a list using recursion

GIVEN DATE

SUBMISSION DATE

SIGN. OF STUDENT

TOTAL
ATTENDANCE PRESENTATION UNDERSTANDING
MARKS

02 02 06 10

SIGN. OF FACULTY

REMARKS
EXPERIMENT NO. 06
6.1 AIM: -

Program to find the length of a list using recursion.

6.2 THEORY:-

Recursion is a programming concept where a function calls itself during its


execution. In this program, the function find_length_recursive calls itself to
calculate the length of the list.
The base case is crucial in recursive functions to prevent infinite recursion. In this
case, if the list is empty, the function returns 0, signaling the end of recursion. List
slicing (lst[1:]) is used to obtain the rest of the list excluding the first element.
This mechanism is key to the recursive reduction of the problem. While recursion
provides an elegant solution, it might not be the most efficient for finding the
length of a list in Python due to the overhead of function calls. Iterative solutions
using loops are often more efficient for this specific task.

6.1 PROGRAM CODE:-

def find_length_recursive(lst):
# Base case: If the list is empty, return 0.
if not lst:
return 0
# Recursive case: Return 1 plus the length of the rest of the list.
else:
return 1 + find_length_recursive(lst[1:])

# Example usage:
my_list = [1, 2, 3, 4, 5]
result = find_length_recursive(my_list)
print(result)
6.2 CONCLUSION:

QUESTIONS:-

Q1) How does the function reduce the problem in each recursive call?

Q2) Define recursion in python?


SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

EXPERIMENT NO. 07 Compute the diameter, circumference and volume of a


sphere using class

GIVEN DATE

SUBMISSION DATE

SIGN. OF STUDENT

TOTAL
ATTENDANCE PRESENTATION UNDERSTANDING
MARKS

02 02 06 10

SIGN. OF FACULTY

REMARKS
EXPERIMENT NO. 07
7.1 AIM: -

Compute the diameter, circumference and volume of a sphere using class

7.2 THEORY:-
A sphere is a perfectly round geometrical object in three-dimensional space that is
the surface of a completely round ball. he radius of a sphere is the distance from
the center of the sphere to any point on its surface. It is constant for a given sphere.
The diameter of a sphere is the distance straight through the center from one point
on the surface to another point on the opposite side. It is twice the radius. The
circumference of a sphere is the distance around its outer edge. The volume of a
sphere is the amount of space enclosed by the sphere. We prompt the user to input
the radius of the sphere. We create an instance of the Sphere class with the
provided radius. We print out the computed diameter, circumference, and volume
of the sphere using the methods of the Sphere class.

Mathematical formulas:
Diameter: D=2r
Circumference: C=2πr
Volume: V=4/3 πr^3
7.3 PROGRAM CODE:-

import math

class Sphere:
def __init__(self, radius):
self.radius = radius

def diameter(self):
return 2 * self.radius

def circumference(self):
return 2 * math.pi * self.radius

def volume(self):
return (4/3) * math.pi * (self.radius ** 3)

# Example usage:
radius = float(input("Enter the radius of the sphere: "))
sphere = Sphere(radius)
print("Diameter of the sphere:", sphere.diameter())
print("Circumference of the sphere:", sphere.circumference())
print("Volume of the sphere:", sphere.volume())
7.4 CONCLUSION:-

QUESTIONS:-

Q1) Explain the difference between a method and a function in Python?

Q2) What is the purpose of using a class in this code?

Q3) How would you handle invalid input (e.g., negative radius) in this code?
SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

EXPERIMENT NO. 08 Program to read a file and capitalize the first letter of
every word in the file

GIVEN DATE

SUBMISSION DATE

SIGN. OF STUDENT

TOTAL
ATTENDANCE PRESENTATION UNDERSTANDING
MARKS

02 02 06 10

SIGN. OF FACULTY

REMARKS
EXPERIMENT NO. 08
8.1 AIM:-

Program to read a file and capitalize the first letter of every word in the file

8.2 THEORY:-

In Python, the open() function is used to open files. It takes two arguments: the
file path and the mode in which to open the file (e.g., 'r' for reading, 'w' for
writing, 'a' for appending). Reading from a file is done using the read() method,
and writing to a file is done using the write() method. Python provides various
methods for string manipulation. In this code, we use the split() method to split
the content of the file into words, and the capitalize() method to capitalize the
first letter of each word. Generator expressions are similar to list
comprehensions but use parentheses instead of square brackets. They generate
values on-the-fly instead of constructing a full list in memory, which can be more
memory-efficient, especially for large datasets.

8.3 PROGRAM CODE:

def capitalize_first_letter(file_path):
with open(file_path, 'r') as file:
content = file.read()

modified_content = ' '.join(word.capitalize() for word in content.split())

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


file.write(modified_content)

# Example usage:
file_path = input("Enter the file path: ")
capitalize_first_letter(file_path)
print("First letter of every word capitalized in the file.")
8.4 CONCLUSION:-

QUESTIONS:-

Q1) How does the open() function work in Python? What are its parameters?

Q2) Explain the difference between reading mode ('r'), writing mode ('w'), and
appending mode ('a') in file handling.

Q3) Describe the difference between a list comprehension and a generator expression .

Q4) How does the capitalize() method work in Python strings? What does it do?
SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

EXPERIMENT NO. 09 Program to remove the “i” th occurrence of given


word in a list where words repeat.

GIVEN DATE

SUBMISSION DATE

SIGN. OF STUDENT

TOTAL
ATTENDANCE PRESENTATION UNDERSTANDING
MARKS

02 02 06 10

SIGN. OF FACULTY

REMARKS
EXPERIMENT NO.9
9.1 AIM:-

Program to remove the “i” th occurrence of given word in a list where words repeat.

9.2 THEORY:-

The function remove_ith_occurrence takes three arguments: word_list (the list of


words), word (the word to remove), and i (the occurrence of the word to
remove). It initializes two variables, count and index, to keep track of the number
of occurrences of the word and the current index in the list, respectively.
It iterates through the list using a while loop and increments count each time the
word is encountered. When the count reaches the desired occurrence (i), it
removes the word at the corresponding index using the pop method. The
example usage demonstrates how to use the function to remove the 2nd
occurrence of the word "apple" from a list of words.
.

9.3 PROGRAM CODE:

def remove_ith_occurrence(word_list, word, i):


count = 0
index = 0

while count < i:


if word_list[index] == word:
count += 1
index += 1

if count == i:
word_list.pop(index - 1)

# Example usage:
words = ['apple', 'banana', 'apple', 'orange', 'apple', 'grape']
word_to_remove = 'apple'
occurrence_to_remove = 2

print("Original list:", words)


remove_ith_occurrence(words, word_to_remove, occurrence_to_remove)
print("After removing", occurrence_to_remove, "occurrence of", word_to_remove + ":", words)
9.4 CONCLUSION:-

QUESTIONS:-

Q1) Why do we use a while loop instead of a for loop in this scenario??

Q2) What happens if the given word does not exist in the list or if the occurrence specified
exceeds the actual occurrences in the list?.

Q3) What are the advantages and disadvantages of using the pop() method to remove

elements from a list?


SHRIRAM INSTITUTE OF ENGINEERING AND
TECHNOLOGY (POLY), PANIV
Department of Computer Engineering

EXPERIMENT NO. 10 Program to create a dictionary with key as first character and
value as words starting with that character

GIVEN DATE

SUBMISSION DATE

SIGN. OF STUDENT

TOTAL
ATTENDANCE PRESENTATION UNDERSTANDING
MARKS

02 02 06 10

SIGN. OF FACULTY

REMARKS
EXPERIMENT NO. 10
10.1 AIM:-

Program to create a dictionary with key as first character and value as words
starting with that Character

10.2 THEORY:-

The function create_word_dictionary takes a list of words as input.


It initializes an empty dictionary word_dict to store the mapping of first
characters to lists of words. It iterates through each word in the input list. For
each word, it checks if the first character (word[0]) is already a key in the
dictionary. If it is, it appends the word to the corresponding list. If it is not, it
creates a new key with the first character and assigns a list containing the word
as its value.
Finally, it returns the populated dictionary.

10.3 PROGRAM CODE:

def create_word_dictionary(words):
word_dict = {}
for word in words:
if word[0] in word_dict:
word_dict[word[0]].append(word)
else:
word_dict[word[0]] = [word]
return word_dict

# Example usage:
word_list = ['apple', 'banana', 'cat', 'dog', 'elephant', 'fish', 'gorilla']
result_dict = create_word_dictionary(word_list)
print("Dictionary with words starting with first character as key:")
print(result_dict)
10.4 CONCLUSION:-

QUESTIONS:-

1. How does the create_word_dictionary function work?

2. What is the purpose of using a dictionary in this code?

3. Why do we use a list as the value in the dictionary instead of a single


word?

4. How would you handle cases where words with different cases (e.g.,
uppercase and lowercase) have the same first character?

You might also like