You are on page 1of 43

JSS MAHAVIDYAPEETHA

JSS ACADEMY OF TECHNICAL EDUCATION, BENGALURU-60


DEPARTMENT OF INFORMATION SCIENCE AND
ENGINEERING
JSSATE Campus, Dr. Vishnuvardhana Main Road, Bengaluru – 560060

IV SEMESTER
PYTHON PROGRAMMING LABORATORY LAB MANUAL

[21CSL46]

Compiled By:

Mrs. Punitha M Mr. Chetan R


Assistant Professor Assistant Professor,
Dept. of Information Science & Dept of Information Science &
Engineering, JSSATEB Engineering, JSSATEB

Signature of Faculty Signature of HOD


JSS MAHAVIDYAPEETHA

JSS ACADEMY OF TECHNICAL EDUCATION, BENGALURU-60


DEPARTMENT OF INFORMATION SCIENCE AND
ENGINEERING

VISION
To emerge as a centre for achieving academic excellence, by producing competent professionals
to meet the global challenges in the field of Information science and Technology.

MISSION
M1:To prepare the students as competent professionals to meet the advancements in the
industry and academia by imparting quality technical education.

M2:To enrich the technical ability of students to face the world with confidence, commitment
and teamwork
.
M3: To inculcate and practice strong techno-ethical values to serve the society.

Program Educational Objectives (PEOs):


PEO1: To demonstrate analytical and technical problem solving abilities.

PEO2: To be conversant in the developments of Information Science and Engineering, leading


towards the employability and higher studies.

PEO3: To engage in research and development leading to new innovations and products.

Program Specific Outcomes (PSOs):


PSO1: Apply the mathematical concepts for solving engineering problems by using appropriate
programming constructs
.
PSO2: Adaptability to software development methodologies.

PSO3: Demonstrate the knowledge towards the domain specific initiatives of Information
Science and Engineering.
Program Outcomes (POs):
Information Science and Engineering Graduates will be able to:

PO1 Apply the knowledge of mathematics, science, engineering fundamentals, and an


Engineering specialization to the solution of complex engineering problems.
PO2 Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
PO3 Design solutions for complex engineering problems and design system components or
processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental
considerations.
PO4 Use research-based knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis of the information to provide valid
conclusions.
PO5 Create, select, and apply appropriate techniques, resources, and modern engineering and
IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
PO6 Apply reasoning informed by the contextual knowledge to assess societal, health, safety,
legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7 Understand the impact of the professional engineering solutions in societal and
environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8 Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
PO9 Function effectively as an individual, and as a member or leader in diverse teams, and in
multidisciplinary settings.
PO10 Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and
receive clear instructions.
PO11 Demonstrate knowledge and understanding of the engineering and management
principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
PO12 Recognize the need for, and have the preparation and ability to engage in independent
and life-long learning in the broadest context of technological change.
Python Programming Laboratory 21CSL46

Course Code 21CSL46 Sem IV


CIE Marks 50 No of contact hours/week 0:0:2
Total Number of Lab Contact hrs 24 SEE Marks 50
Exam ccontact
Hours Duration 3 hrs Credits 1

PROGRAM -1

a) Write a python program to find the best of two test average marks out of three test’s marks
accepted from the user.

b) Develop a Python program to check whether a given number is palindrome or not and also
count the number of occurrences of each digit in the input number.

PROGRAM -2

a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts a value
for N (where N >0) as input and pass this value to the function. Display suitable error message if
the condition for input value is not followed.

b) Develop a python program to convert binary to decimal, octal to hexadecimal using functions.

PROGRAM -3

a) Write a Python program that accepts a sentence and find the number of words, digits,
uppercase letters, and lowercase letters.

b) Write a Python program to find the string similarity between two given strings.

PROGRAM -4

a) Write a python program to implement insertion sort and merge sort using lists

b) Write a program to convert Roman numbers into integer values using dictionaries.

PROGRAM -5

a) Write a function called isphonenumber( ) to recognize a pattern 415-555-4242 without using


regular expression and also write the code to recognize the same pattern using regular
expression.

b) Develop a Python program that could search the text in a file for phone numbers
(+919900889977) and email addresses (sample@gmail.com)
PROGRAM -6

a) Write a python program to accept a file name from the user and perform the following
operations

1. Display the first N line of the file

2. Find the frequency of occurrence of the word accepted by the user in the file

b) Write a Python program to create a ZIP file of a particular folder that contains several files
inside it.

PROGRAM -7

a) By using the concept of inheritance write a python program to find the area of a triangle,
circle, and rectangle.

b) Write a Python program by creating a class called Employee to store the details of Name,
Employee_ID, Department, and Salary, and implement a method to update the salary of
employees belonging to a given department.

PROGRAM -8

a) Write a Python program to find whether the given input is palindrome or not (for both string
and integer) using the concept of polymorphism and inheritance.

PROGRAM -9

a) Write a python program to download the all XKCD comics

b) Demonstrate a python program to read the data from the spreadsheet and write the data into
the spreadsheet

PROGRAM -10

a) Write a python program to combine select pages from many PDFs

b) Write a python program to fetch current weather data from the JSON file

PART B Practical Based Learning

A problem statement for each batch is to be generated in consultation with the co-examiner and
student should develop an algorithm, program and execute the program for the given problem
with appropriate outputs.
Lesson plan
Python Programming Laboratory 21CSL46

Pre-requisites:
Knowledge about any programming language.
Learning Objectives:
CLO 1. Demonstrate the use of IDLE or PyCharm IDE to create Python Applications

CLO 2. Using Python programming language to develop programs for solving real-
world problems.

CLO 3. Implement the Object-Oriented Programming concepts in Python.

CLO 4. Appraise the need for working with various documents like Excel, PDF, Word
and Others

CLO 5. Demonstrate regular expression using python programming.

Course Outcomes:

CO.NO. COURSE OUTCOMES BLL


C218.1 Apply and analyze the principles of loops and functions. L3
Evaluate and design strategies for manipulating strings, lists, tuples, and
C218.2 L4
dictionaries.
Discover advanced operations involving regular expressions and file
C218.3 L3
systems.
C218.4 Interpret the concepts of Object-Oriented Programming in Python. L2
Synthesize and justify the need for web scraping and working with PDF,
C218.5 L2
JSON, and other file formats.
Sl. Program CO Mate
No rial
Lab Cycle Programs

Aim: Introduce the Python fundamentals, data types, operators, flow control and
exception handling in Python
a) Write a python program to find the best of two test average marks out of three test’s CO1 TB1
1
marks accepted from the user.
b) Develop a Python program to check whether a given number is palindrome or not and
also count the number of occurrences of each digit in the input number.
Aim: Demonstrating creation of functions, passing parameters and return values
a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which accepts a
value for N (where N >0) as input and pass this value to the function. Display suitable CO1 TB1
2
error message if the condition for input value is not followed.
b) Develop a python program to convert binary to decimal, octal to hexadecimal using
functions.
Aim: Demonstration of manipulation of strings using string methods
a) Write a Python program that accepts a sentence and find the number of words, digits, CO2 TB1
3
uppercase letters and lowercase letters.
b) Write a Python program to find the string similarity between two given strings
Aim: Discuss different collections like list, tuple and dictionary
4 a) Write a python program to implement insertion sort and merge sort using lists CO2 TB1
b) Write a program to convert roman numbers in to integer values using dictionaries.
Aim: Demonstration of pattern recognition with and without using regular
expressions
a) Write a function called isphonenumber () to recognize a pattern 415-555-4242 without
5 using regular expression and also write the code to recognize the same pattern using CO3 TB1
regular expression.
b) Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses (sample@gmail.com)
Aim: Demonstration of reading, writing and organizing files.
a) Write a python program to accept a file name from the user and perform the following
operations
6 1. Display the first N line of the file CO3 TB1
2. Find the frequency of occurrence of the word accepted from the user in the file
b) Write a python program to create a ZIP file of a particular folder which contains
several files inside it.
Aim: Demonstration of the concepts of classes, methods, objects and inheritance
a) By using the concept of inheritance write a python program to find the area of
triangle, circle and rectangle. TB3
7 CO4
b) Write a python program by creating a class called Employee to store the details of
Name, Employee_ID, Department and Salary, and implement a method to update salary
of employees belonging to a given department.
Aim: Demonstration of classes and methods with polymorphism and overriding
8 a) Write a python program to find the whether the given input is palindrome or not (for CO4 TB3
both string and integer) using the concept of polymorphism and inheritance.
Aim: Demonstration of working with excel spreadsheets and web scraping
a) Write a python program to download the all XKCD comics TB1
9 CO5
b) Demonstrate python program to read the data from the spreadsheet and write the data
in to the spreadsheet
Aim: Demonstration of working with PDF, word and JSON files
10 a) Write a python program to combine select pages from many PDFs CO5 TB1
b) Write a python program to fetch current weather data from the JSON file

Text Books

Sl.No Book Type Code Author/Title/Publishers

Al Sweigart, “Automate the Boring Stuff with


1. Text Book TB1 Python”,1stEdition, No Starch Press, 2015. (Available under CC-
BY-NC-SA license at https://automatetheboringstuff.com/)
2. Text Book TB2 Reema Thareja “Python Programming Using Problem Solving
Approach” Oxford University Press.
Allen B. Downey, “Think Python: How to Think Like a
3. Text Book TB3 Computer Scientist”, 2nd Edition, Green Tea Press, 2015.
(Available under CC-BY-NC license at
http://greenteapress.com/thinkpython2/thinkpython2.pdf)
CONTINUOUS EVALUATION PROCEDURE
Each program/Experiment = Total = 30m
(Viva=10m,Record/observation=5+5m, conduction= 10m)

Sl. USN Student Program1/1A/1 Program2 Program 3 Program Average


No. Name n

E V R T E V R T

Internal Assessment Marks= 20m


CONTENTS
Sl.No. Programs Page NO.
a) Write a python program to find the best of two test average marks out of three
test’s marks accepted from the user.
1. 1
b) Develop a Python program to check whether a given number is palindrome or
not and also count the number of occurrences of each digit in the input number.
a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program which
accepts a value for N (where N >0) as input and pass this value to the function.
2. Display suitable error message if the condition for input value is not followed. 3
b) Develop a python program to convert binary to decimal, octal to hexadecimal
using functions.
a) Write a Python program that accepts a sentence and find the number of words,
3. digits, uppercase letters and lowercase letters. 5
b) Write a Python program to find the string similarity between two given strings
a) Write a python program to implement insertion sort and merge sort using lists
4. b) Write a program to convert roman numbers in to integer values using 7
dictionaries.
a) Write a function called isphonenumber () to recognize a pattern 415-555-4242
without using regular expression and also write the code to recognize the same
5. pattern using regular expression. 11
b) Develop a python program that could search the text in a file for phone numbers
(+919900889977) and email addresses (sample@gmail.com)
a) Write a python program to accept a file name from the user and perform the
following operations
1. Display the first N line of the file
6. 14
2. Find the frequency of occurrence of the word accepted from the user in the file
b) Write a python program to create a ZIP file of a particular folder which contains
several files inside it.
a) By using the concept of inheritance write a python program to find the area of
triangle, circle and rectangle.
7. b) Write a python program by creating a class called Employee to store the details 17
of Name, Employee_ID, Department and Salary, and implement a method to
update salary of employees belonging to a given department.
a) Write a python program to find the whether the given input is palindrome or not
8. 21
(for both string and integer) using the concept of polymorphism and inheritance.
a) Write a python program to download the all XKCD comics
9. b) Demonstrate python program to read the data from the spreadsheet and write the 23
data in to the spreadsheet
a) Write a python program to combine select pages from many PDFs
10. 28
b) Write a python program to fetch current weather data from the JSON file
11. Viva Questions 32
Python Programming Lab Manual 21CSL46

PROGRAM -1

1a) Write a Python program to find the best of two test average marks out of
three test marks accepted by the user.

m1 = int(input("Enter marks for test1 : "))

m2 = int(input("Enter marks for test2 : "))

m3 = int(input("Enter marks for test3 : "))

if m1 <= m2 and m1 <= m3:

avgMarks = (m2+m3)/2

elif m2 <= m1 and m2 <= m3:

avgMarks = (m1+m3)/2

elif m3 <= m1 and m2 <= m2:

avgMarks = (m1+m2)/2

print("Average of best two test marks out of three test’s marks is", avgMarks);

OUTPUT

Enter marks for test1: 45

Enter marks for test2: 39

Enter marks for test3: 48

Average of best two test marks out of three test’s marks is 46.5

Dept. of ISE, JSSATEB 1


Python Programming Lab Manual 21CSL46

1b) Develop a Python program to check whether a given number is


palindrome or not and also count the number of occurrences of each digit in
the input number.

val = int(input("Enter a value : "))

str_val = str(val)

if str_val == str_val[::-1]:

print("Palindrome")

else:

print("Not Palindrome")

for i in range(10):

if str_val.count(str(i)) > 0:

print(str(i),"appears", str_val.count(str(i)), "times");

OUTPUT:

Enter a value: 1234234

Not Palindrome

1 appears 1 times

2 appears 2 times

3 appears 2 times

4 appears 2 times

Enter a value: 12321

Palindrome

1 appears 2 times

2 appears 2 times

3 appears 1 times

Dept. of ISE, JSSATEB 2


Python Programming Lab Manual 21CSL46

PROGRAM -2

2a) Defined as a function F as Fn = Fn-1 + Fn-2. Write a Python program that


accepts a value for N (where N >0) as input and pass this value to the
function. Display a suitable error message if the condition for input value is
not followed.

def fn(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fn(n-1) + fn(n-2)

num = int(input("Enter a number : "))

if num > 0:
print("fn(", num, ") = ",fn(num) , sep ="")
else:
print("Error in input")

OUTPUT:

Enter a number : 5

fn(5) = 3

Dept. of ISE, JSSATEB 3


Python Programming Lab Manual 21CSL46

2b) Develop a python program to convert binary to decimal, octal to


hexadecimal using functions.

def binary_to_decimal(binary):
decimal = 0
power = 0
while binary != 0:
last_digit = binary % 10
decimal += last_digit * (2 ** power)
binary //= 10
power += 1
return decimal

def octal_to_hexadecimal(octal):
decimal = 0
power = 0
while octal != 0:
last_digit = octal % 10
decimal += last_digit * (8 ** power)
octal //= 10
power += 1

hexadecimal = ""
hex_digits = "0123456789ABCDEF"
while decimal != 0:
remainder = decimal % 16
hexadecimal = hex_digits[remainder] + hexadecimal
decimal //= 16

return hexadecimal

# Binary to Decimal conversion


binary_number = input("Enter a binary number: ")
decimal_number = binary_to_decimal(int(binary_number))
print("Decimal equivalent:", decimal_number)

# Octal to Hexadecimal conversion


octal_number = input("Enter an octal number: ")
hexadecimal_number = octal_to_hexadecimal(int(octal_number))
print("Hexadecimal equivalent:", hexadecimal_number)
OUTPUT:
Enter a binary number : 10111001
185
Enter a octal number : 675
1BD

Dept. of ISE, JSSATEB 4


Python Programming Lab Manual 21CSL46

PROGRAM -3

3a) Write a Python program that accepts a sentence and find the number of
words, digits, uppercase letters, and lowercase letters.

def analyze_sentence(sentence):
word_count = len(sentence.split())

digit_count = 0
uppercase_count = 0
lowercase_count = 0

for char in sentence:


if char.isdigit():
digit_count += 1
elif char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1

return word_count, digit_count, uppercase_count, lowercase_count

user_sentence = input("Enter a sentence: ")


word_count, digit_count, uppercase_count, lowercase_count = analyze_sentence(user_sentence)

print("Number of words:", word_count)


print("Number of digits:", digit_count)
print("Number of uppercase letters:", uppercase_count)
print("Number of lowercase letters:", lowercase_count)

OUTPUT:

Enter a sentence : Rama went to Devaraja market to pick 2 kgs of vegetable

This sentence has 11 words

This sentence has 1 digits 2 upper case letters 42 lower case letters

Dept. of ISE, JSSATEB 5


Python Programming Lab Manual 21CSL46

3b) Write a Python program to find the string similarity between two given
strings.

str1 = input("Enter String 1 \n")


str2 = input("Enter String 2 \n")

if len(str2) < len(str1):


short = len(str2)
long = len(str1)
else:
short = len(str1)
long = len(str2)
matchCnt = 0
for i in range(short):
if str1[i] == str2[i]:
matchCnt += 1
print("Similarity between two said strings:")
print(matchCnt/long)
OUTPUT:

Enter String 1
Python Exercises
Enter String 2
Python Exercises
Similarity between two said strings:
1.0
Enter String 1
Python Exercises
Enter String 2
Python Exercise
Similarity between two said strings:
0.9375

Dept. of ISE, JSSATEB 6


Python Programming Lab Manual 21CSL46

PROGRAM -4

4a) Write a python program to implement insertion sort and merge sort using
lists.

import random

def merge_sort(rec):

if len(rec) > 1:

mid = len(rec) // 2

left_half = rec[:mid]

right_half = rec[mid:]

merge_sort(left_half)
merge_sort(right_half)
i=j=k=0

while i < len(left_half) and j < len(right_half):


if left_half[i] < right_half[j]:
rec[k] = left_half[i]
i += 1
else:
rec[k] = right_half[j]
j += 1
k += 1

while i < len(left_half):

rec[k] = left_half[i]

i += 1

Dept. of ISE, JSSATEB 7


Python Programming Lab Manual 21CSL46

k += 1

while j < len(right_half):


rec[k] = right_half[j]
j += 1
k += 1
return rec

def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j=i-1
while j >= 0 and key < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key

my_list = []
for i in range(10):

my_list.append(random.randint(0, 999))

print("\nUnsorted List")

print(my_list)

print("Sorting using Insertion Sort")

insertion_sort(my_list)

print(my_list)

my_list = []

for i in range(10):

Dept. of ISE, JSSATEB 8


Python Programming Lab Manual 21CSL46

my_list.append(random.randint(0, 999))

print("\nUnsorted List")

print(my_list)

print("Sorting using Merge Sort")

merge_sort(my_list)

print(my_list)

OUTPUT:

Unsorted List

[932, 111, 226, 685, 543, 589, 918, 539, 294, 717]

Sorting using Insertion Sort

[111, 226, 294, 539, 543, 589, 685, 717, 918, 932]

Unsorted List

[613, 176, 828, 265, 65, 326, 359, 919, 514, 868]

Sorting using Merge Sort

[65, 176, 265, 326, 359, 514, 613, 828, 868, 919]

Dept. of ISE, JSSATEB 9


Python Programming Lab Manual 21CSL46

4b) Write a program to convert Roman numbers into integer values using
dictionaries.

def roman2Dec(romStr):

roman_dict ={'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}

# Analyze string backwards

romanBack = list(romStr)[::-1]

value = 0

# To keep track of order

rightVal = roman_dict[romanBack[0]]

for numeral in romanBack:

leftVal = roman_dict[numeral]

# Check for subtraction

if leftVal < rightVal:

value -= leftVal

else:

value += leftVal

rightVal = leftVal

return value

romanStr = input("Enter a Roman Number : ")

print(roman2Dec(romanStr))

OUTPUT:
Enter a Roman Number: XVII
17

Enter a Roman Number: MLXVI


1066

Dept. of ISE, JSSATEB 10


Python Programming Lab Manual 21CSL46

PROGRAM -5

5a) Write a function called isphonenumber( ) to recognize a pattern 415-555-


4242 without using regular expression and also write the code to recognize
the same pattern using regular expression.

import re

def isphonenumber(numStr):

if len(numStr) != 12:

return False

for i in range(len(numStr)):

if i==3 or i==7:

if numStr[i] != "-":

return False

else:

if numStr[i].isdigit() == False:

return False

return True

def chkphonenumber(numStr):

ph_no_pattern = re.compile(r'^\d{3}-\d{3}-\d{4}$')

if ph_no_pattern.match(numStr):

return True

else:

return False

Dept. of ISE, JSSATEB 11


Python Programming Lab Manual 21CSL46

ph_num = input("Enter a phone number : ")


print("Without using Regular Expression")
if isphonenumber(ph_num):
print("Valid phone number")
else:

print("Invalid phone number")

print("Using Regular Expression")


if chkphonenumber(ph_num):
print("Valid phone number")
else:
print("Invalid phone number")

OUTPUT:

Enter a phone number: 444-654-5656

Without using Regular Expression

Valid phone number

Using Regular Expression

Valid phone number

Dept. of ISE, JSSATEB 12


Python Programming Lab Manual 21CSL46

5b) Develop a Python program that could search the text in a file for phone
numbers (+919900889977) and email addresses (sample@gmail.com)

import re

# Define the regular expression for phone numbers

phone_regex = re.compile(r'\+\d{12}')

email_regex = re.compile(r'[A-Za-z0-9._]+@[A-Za-z0-9]+\.[A-Z|a-z]{2,}')

# Open the file for reading

with open('example.txt', 'r') as f:

# Loop through each line in the file

for line in f:

# Search for phone numbers in the line

matches = phone_regex.findall(line)

# Print any matches found

for match in matches:

print(match)

matches = email_regex.findall(line)

# Print any matches found

for match in matches:

print(match)

OUTPUT:
+918151894220
+829392938876
+918768456234
prakash81.82@gmail.in

Dept. of ISE, JSSATEB 13


Python Programming Lab Manual 21CSL46

PROGRAM -6

6a) Write a python program to accept a file name from the user and perform
the following operations.

1. Display the first N line of the file

2. Find the frequency of occurrence of the word accepted by the user in the
file

import os.path

import sys

fname = input("Enter the filename : ")

if not os.path.isfile(fname):

print("File", fname, "doesn't exists")

sys.exit(0)

infile = open(fname, "r")

lineList = infile.readlines()

for i in range(20):

print(i+1, ":", lineList[i])

word = input("Enter a word : ")

cnt = 0

for line in lineList:

cnt += line.count(word)

print("The word", word, "appears", cnt, "times in the file")

Dept. of ISE, JSSATEB 14


Python Programming Lab Manual 21CSL46

OUTPUT:

Enter the filename : example.txt


1 : this is phone number +918151894220
2 : no phone number here
3 : here we have one +829392938876
4 : we have an email prakash81.82@gmail.in and a number +918768456234
5 : nothing of that sort here
6 : Better hope the life-inspector doesn't come around while you have your
7 : life in such a mess.
8 : You can create your own opportunities this week. Blackmail a senior
executive.
9 : Be different: conform.
10 : Be cheerful while you are alive.
11 : -- Phathotep, 24th Century B.C.
12 : Q: How many journalists does it take to screw in a light bulb?
13 : A: Three. One to report it as an inspired government program to bring
14 : light to the people, one to report it as a diabolical government plot
15 : to deprive the poor of darkness, and one to win a Pulitzer prize for
16 : reporting that Electric Company hired a light bulb-assassin to break
17 : the bulb in the first place.
18 : Q: Why did the astrophysicist order three hamburgers?
19 : A: Because he was hungry.
20 : Q: Why haven't you graduated yet?
Enter a word : the
The word the appears 7 times in the file.

Dept. of ISE, JSSATEB 15


Python Programming Lab Manual 21CSL46

6b) Write a Python program to create a ZIP file of a particular folder that
contains several files inside it.

import os

import sys

import pathlib

import zipfile

dirName = input("Enter Directory name that you want to backup : ")

if not os.path.isdir(dirName):
print("Directory", dirName, "doesn't exists")
sys.exit(0)

curDirectory = pathlib.Path(dirName)

with zipfile.ZipFile("myZip.zip", mode="w") as archive:

for file_path in curDirectory.rglob("*"):

archive.write(file_path, arcname=file_path.relative_to(curDirectory))

if os.path.isfile("myZip.zip"):

print("Archive", "myZip.zip", "created successfully")


else:
print("Error in creating zip archive")

OUTPUT:
Enter Directory name that you want to backup : zipDemo
Archive myZip.zip created successfully.

Dept. of ISE, JSSATEB 16


Python Programming Lab Manual 21CSL46

PROGRAM -7

7a) By using the concept of inheritance write a python program to find the
area of a triangle, circle, and rectangle.

import math

class Shape:

def __init__(self):

self.area = 0

self.name = ""

def showArea(self):
print("The area of the", self.name, "is", self.area, "units")

class Circle(Shape):
def __init__(self,radius):
self.area = 0
self.name = "Circle"
self.radius = radius

def calcArea(self):

self.area = math.pi * self.radius * self.radius

class Rectangle(Shape):

def __init__(self,length,breadth):
self.area = 0
self.name = "Rectangle"
self.length = length
self.breadth = breadth

Dept. of ISE, JSSATEB 17


Python Programming Lab Manual 21CSL46

def calcArea(self):
self.area = self.length * self.breadth

class Triangle(Shape):
def __init__(self,base,height):
self.area = 0
self.name = "Triangle"
self.base = base
self.height = height

def calcArea(self):
self.area = self.base * self.height / 2

c1 = Circle(5)
c1.calcArea()
c1.showArea()

r1 = Rectangle(5, 4)
r1.calcArea()
r1.showArea()

t1 = Triangle(3, 4)
t1.calcArea()
t1.showArea()

OUTPUT:
The area of the Circle is 78.53981633974483 units
The area of the Rectangle is 20 units
The area of the Triangle is 6.0 units

Dept. of ISE, JSSATEB 18


Python Programming Lab Manual 21CSL46

7b) Write a Python program by creating a class called Employee to store the
details of Name, Employee_ID, Department, and Salary, and implement a
method to update the salary of employees belonging to a given department.

class Employee:
def __init__(self):
self.name = ""
self.empId = ""
self.dept = ""
self.salary = 0

def getEmpDetails(self):
self.name = input("Enter Employee name : ")
self.empId = input("Enter Employee ID : ")
self.dept = input("Enter Employee Dept : ")
self.salary = int(input("Enter Employee Salary : "))

def showEmpDetails(self):
print("Employee Details")
print("Name : ", self.name)
print("ID : ", self.empId)
print("Dept : ", self.dept)
print("Salary : ", self.salary)

def updtSalary(self):
self.salary = int(input("Enter new Salary : "))
print("Updated Salary", self.salary)

e1 = Employee()
e1.getEmpDetails()

Dept. of ISE, JSSATEB 19


Python Programming Lab Manual 21CSL46

e1.showEmpDetails()
e1.updtSalary()
OUTPUT:
Enter Employee name: Sameer

Enter Employee ID: A123

Enter Employee Dept: CSE

Enter Employee Salary: 85750

Employee Details

Name: Sameer

ID: A123

Dept: CSE

Salary: 85750

Enter new Salary: 88800

Updated Salary 88800

Dept. of ISE, JSSATEB 20


Python Programming Lab Manual 21CSL46

PROGRAM -8

8a) Write a Python program to find whether the given input is palindrome or
not (for both string and integer) using the concept of polymorphism and
inheritance.

class PaliStr:
def __init__(self):
self.isPali = False

def chkPalindrome(self, myStr):


if myStr == myStr[::-1]:
self.isPali = True
else:
self.isPali = False

return self.isPali

class PaliInt(PaliStr):
def __init__(self):
self.isPali = False

def chkPalindrome(self, val):


temp = val
rev = 0
while temp != 0:
dig = temp % 10
rev = (rev*10) + dig
temp = temp //10

if val == rev:

Dept. of ISE, JSSATEB 21


Python Programming Lab Manual 21CSL46

self.isPali = True
else:
self.isPali = False

return self.isPali

st = input("Enter a string : ")

stObj = PaliStr()
if stObj.chkPalindrome(st):
print("Given string is a Palindrome")
else:
print("Given string is not a Palindrome")

val = int(input("Enter a integer : "))

intObj = PaliInt()
if intObj.chkPalindrome(val):
print("Given integer is a Palindrome")
else:
print("Given integer is not a Palindrome")

OUTPUT:
Enter a string : madam
Given string is a Palindrome
Enter a integer : 567587
Given integer is not a Palindrome
Enter a string : INDIA
Given string is not a Palindrome
Enter a integer : 6789876
Given integer is a Palindrome

Dept. of ISE, JSSATEB 22


Python Programming Lab Manual 21CSL46

PROGRAM -9

9a) Write a Python program to download all XKCD comics.

import requests
import os
from bs4 import BeautifulSoup

# Set the URL of the first XKCD comic


url = 'https://xkcd.com/1/'

# Create a folder to store the comics


if not os.path.exists('xkcd_comics'):
os.makedirs('xkcd_comics')

# Loop through all the comics


while True:
# Download the page content
res = requests.get(url)
res.raise_for_status()

# Parse the page content using BeautifulSoup


soup = BeautifulSoup(res.text, 'html.parser')

# Find the URL of the comic image


comic_elem = soup.select('#comic img')
if comic_elem == []:
print('Could not find comic image.')
else:
comic_url = 'https:' + comic_elem[0].get('src')

Dept. of ISE, JSSATEB 23


Python Programming Lab Manual 21CSL46

# Download the comic image


print(f'Downloading {comic_url}...')
res = requests.get(comic_url)
res.raise_for_status()

# Save the comic image to the xkcd_comics folder


image_file = open(os.path.join('xkcd_comics', os.path.basename(comic_url)), 'wb')
for chunk in res.iter_content(100000):
image_file.write(chunk)
image_file.close()

# Get the URL of the previous comic


prev_link = soup.select('a[rel="prev"]')[0]
if not prev_link:
break
url = 'https://xkcd.com' + prev_link.get('href')

print('All comics downloaded.')

OUTPUT:

Downloading https://imgs.xkcd.com/comics/barrel_cropped_(1).jpg...

Downloading https://imgs.xkcd.com/comics/radians_are_cursed.png...

Downloading https://imgs.xkcd.com/comics/presents_for_biologists.png...

Downloading https://imgs.xkcd.com/comics/launch_window.png...

Downloading https://imgs.xkcd.com/comics/obituary_editor.png...

Downloading https://imgs.xkcd.com/comics/fanservice.png...

Downloading https://imgs.xkcd.com/comics/hand_dryers.png...

Dept. of ISE, JSSATEB 24


Python Programming Lab Manual 21CSL46

9b) Demonstrate a python program to read the data from the spreadsheet and
write the data into the spreadsheet.

from openpyxl import Workbook


from openpyxl.styles import Font

wb = Workbook()
sheet = wb.active
sheet.title = "Language"
wb.create_sheet(title = "Capital")

lang = ["Kannada", "Telugu", "Tamil"]


state = ["Karnataka", "Telangana", "Tamil Nadu"]
capital = ["Bengaluru", "Hyderabad", "Chennai"]
code =['KA', 'TS', 'TN']
sheet.cell(row = 1, column = 1).value = "State"
sheet.cell(row = 1, column = 2).value = "Language"
sheet.cell(row = 1, column = 3).value = "Code"

ft = Font(bold=True)
for row in sheet["A1:C1"]:
for cell in row:
cell.font = ft

for i in range(2,5):
sheet.cell(row = i, column = 1).value = state[i-2]
sheet.cell(row = i, column = 2).value = lang[i-2]
sheet.cell(row = i, column = 3).value = code[i-2]

wb.save("demo.xlsx")

Dept. of ISE, JSSATEB 25


Python Programming Lab Manual 21CSL46

sheet = wb["Capital"]
sheet.cell(row = 1, column = 1).value = "State"
sheet.cell(row = 1, column = 2).value = "Capital"
sheet.cell(row = 1, column = 3).value = "Code"

ft = Font(bold=True)
for row in sheet["A1:C1"]:
for cell in row:
cell.font = ft

for i in range(2,5):
sheet.cell(row = i, column = 1).value = state[i-2]
sheet.cell(row = i, column = 2).value = capital[i-2]
sheet.cell(row = i, column = 3).value = code[i-2]

wb.save("demo.xlsx")
srchCode = input("Enter state code for finding capital ")
for i in range(2,5):
data = sheet.cell(row = i, column = 3).value
if data == srchCode:
print("Corresponding capital for code", srchCode, "is", sheet.cell(row = i,
column = 2).value)

sheet = wb["Language"]
srchCode = input("Enter state code for finding language ")
for i in range(2,5):
data = sheet.cell(row = i, column = 3).value
if data == srchCode:
print("Corresponding language for code", srchCode, "is", sheet.cell(row = i,
column = 2).value)

Dept. of ISE, JSSATEB 26


Python Programming Lab Manual 21CSL46

wb.close()
OUTPUT:
Enter state code for finding capital KA
Corresponding capital for code KA is Bengaluru
Enter state code for finding language TS
Corresponding language for code TS is Telugu

Dept. of ISE, JSSATEB 27


Python Programming Lab Manual 21CSL46

PROGRAM -10

10a) Write a Python program to combine select pages from many PDFs.

from PyPDF2 import PdfWriter, PdfReader

num = int(input("Enter page number you want combine from multiple documents
"))

pdf1 = open('birds.pdf', 'rb')


pdf2 = open('birdspic.pdf', 'rb')
pdf_writer = PdfWriter()

pdf1_reader = PdfReader(pdf1)
page = pdf1_reader.pages[num - 1]
pdf_writer.add_page(page)

pdf2_reader = PdfReader(pdf2)
page = pdf2_reader.pages[num - 1]
pdf_writer.add_page(page)

with open('output.pdf', 'wb') as output:


pdf_writer.write(output)

OUTPUT:

Enter page number you want combine from multiple documents - 3

Initially take any two pdf files and chose first three pages to combine and give the
result in an output file.

Dept. of ISE, JSSATEB 28


Python Programming Lab Manual 21CSL46

10b) Write a Python program to fetch current weather data from the JSON
file.

import json

# Load the JSON data from file

with open('weather_data.json') as f:

data = json.load(f)

# Extract the required weather data

current_temp = data['main']['temp']

humidity = data['main']['humidity']

weather_desc = data['weather'][0]['description']

# Display the weather data

print(f"Current temperature: {current_temp}°C")

print(f"Humidity: {humidity}%")

print(f"Weather description: {weather_desc}")

JSON file:
{
"coord": {
"lon": -73.99,
"lat": 40.73
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",

Dept. of ISE, JSSATEB 29


Python Programming Lab Manual 21CSL46

"icon": "01d"
} ],
"base": "stations",
"main": {
"temp": 15.45,
"feels_like": 12.74,
"temp_min": 14.44,
"temp_max": 16.11,
"pressure": 1017,
"humidity": 64 },
"visibility": 10000,
"wind": {
"speed": 4.63,
"deg": 180 },
"clouds": {
"all": 1 },
"dt": 1617979985,
"sys": {
"type": 1,
"id": 5141,
"country": "US",
"sunrise": 1617951158,
"sunset": 1618000213 },
"timezone": -14400,
"id": 5128581,
"name": "New York",
"cod": 200
}

Dept. of ISE, JSSATEB 30


Python Programming Lab Manual 21CSL46

OUTPUT:
Current temperature: 15.45°C
Humidity: 64%
Weather description: clear sky

Dept. of ISE, JSSATEB 31


Python Programming Lab Manual 21CSL46

VIVA QUESTIONS:
What is Python?
1. Python is one of the most widely-used and popular programming languages, was developed by Guido van
Rossum and released first on February 20, 1991.
2. Python is a free and open-source language with a very simple and clean syntax which makes it easy for
developers to learn Python.
3. It supports object-oriented programming and is most commonly used to perform general-purpose
programming.
4. Python is used in several domains like Data Science, Machine Learning, Deep Learning, Artificial
Intelligence, Scientific Computing Scripting, Networking, Game Development Web Development, Web
Scraping, and various other domains, System Scripting, Software Development, Complex Mathematics.
What are the benefits of using Python language as a tool in the present scenario?
The following are the benefits of using Python language:
Object-Oriented Language, High-Level Language, Dynamically Typed language, Extensive support Libraries,
Presence of third-party modules, Open source and community development, Portable and Interactive, Portable
across Operating systems.
Is Python a compiled language or an interpreted language?
Python is a partially compiled language and partially interpreted language. ‘#’ is used to comment on
everything that comes after on the line.
Difference between a Mutable datatype and an Immutable data type?
Mutable data types can be edited i.e., they can change at runtime. Eg – List, Dictionary, etc.
Immutable data types can not be edited i.e., they can not change at runtime. Eg – String, Tuple, etc.
What is a lambda function?
A lambda function is an anonymous function. This function can have any number of parameters but, can have
just one statement.
Pass means performing no operation or in other words, it is a placeholder in the compound statement, where
there should be a blank left and nothing has to be written there.

Python provides various web frameworks to develop web applications.


The popular python web frameworks are Django, Pyramid, Flask.
▪ Python's standard library supports for E-mail processing, FTP, IMAP, and other Internet protocols.
▪ Python's SciPy and NumPy help in scientific and computational application development.

Dept. of ISE, JSSATEB 32


Python Programming Lab Manual 21CSL46

▪ Python's Tkinter library supports to create desktop-based GUI applications.


What is the difference between / and // in Python?
// represents floor division whereas / represents precise division. 5//2 = 2 5/2 = 2.5
Yes, indentation is required in Python. A Python interpreter can be informed that a group of statements
belongs to a specific block of code by using Python indentation. Indentations make the code easy to read for
developers in all programming languages but in Python, it is very important to indent the code in a specific
order.

What is Scope in Python?


The location where we can find a variable and also access it if required is called the scope of a variable.
Python Local variable: Local variables are those that are initialized within a function and are unique to that
function. It cannot be accessed outside of the function.
Python Global variables: Global variables are the ones that are defined and declared outside any function
and are not specified to any function.
Module-level scope: It refers to the global objects of the current module accessible in the program.
Outermost scope: It refers to any built-in names that the program can call. The name referenced is located last
among the objects in this scope.

Python documentation strings (or docstrings) provide a convenient way of associating documentation with
Python modules, functions, classes, and methods.
Declaring Docstrings: The docstrings are declared using ”’triple single quotes”’ or “””triple double quotes”””
just below the class, method, or function declaration. All functions should have a docstring.
Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the
help function.

What is slicing in Python?


Python Slicing is a string operation for extracting a part of the string, or some part of a list. With this operator,
one can specify where to start the slicing, where to end, and specify the step. List slicing returns a new list
from the existing list.

PIP is an acronym for Python Installer Package which provides a seamless interface to install various
Python modules. It is a command-line tool that can search for packages over the internet and install them
without any user interaction.

Dept. of ISE, JSSATEB 33

You might also like