0% found this document useful (0 votes)
5 views52 pages

Python Lab Manual 2025-ETE-R Section

The document is a laboratory manual for the Introduction to Python Programming course at Bangalore Institute of Technology for the academic year 2024-2025. It outlines the institute's vision and mission, department goals, course objectives, and expected outcomes for students, along with a detailed schedule of experiments and general lab guidelines. The manual also provides an overview of Python programming, including syntax, data types, and practical applications through various programming exercises.

Uploaded by

gowdanandish953
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)
5 views52 pages

Python Lab Manual 2025-ETE-R Section

The document is a laboratory manual for the Introduction to Python Programming course at Bangalore Institute of Technology for the academic year 2024-2025. It outlines the institute's vision and mission, department goals, course objectives, and expected outcomes for students, along with a detailed schedule of experiments and general lab guidelines. The manual also provides an overview of Python programming, including syntax, data types, and practical applications through various programming exercises.

Uploaded by

gowdanandish953
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/ 52

BANGALORE INSTITUTE OF TECHNOLOGY

Autonomous Institute, Affiliated to VTU


K.R. ROAD, V.V. PURA, BENGALURU -560 004

Department of
Electronics & Telecommunication Engineering

Laboratory Manual

Introduction to Python Programming Laboratory Manual


BPLCK205B

II Semester

Academic year: 2024-2025


BANGALORE INSTITUTE OF TECHNOLOGY
(Autonomous Institute , Affiliated to VTU )
K.R. Road, V.V. Puram, Bengaluru – 560 004. Phone: 26613237/26615865

VISION OF THE INSTITUTE

To establish and develop the Institute as a centre of higher learning, ever abreast with expanding
horizon of knowledge in the field of engineering and technology, with entrepreneurial thinking,
leadership excellence for life-long success and solve societal problem.

MISSION OF THE INSTITUTE

1. Provide high quality education in the engineering disciplines from the undergraduate through doctoral levels
with creative academic and professional programs.

2. Develop the Institute as a leader in Science, Engineering, Technology and management, Research and apply
knowledge for the benefit of society.

3. Establish mutual beneficial partnerships with industry, alumni, local, state and central governments by public
service assistance and collaborative research.

4. Inculcate personality development through sports, cultural and extracurricular


activities and engage in the social, economic and professional challenges.
DEPARTMENT VISION

Empower every student to be Creative and Productive in the field of Electronics


and Telecommunication Engineering by imparting excellent Technical
Education and inculcating Human Values.
DEPARMENT MISSION

1. To make our Students acquaint with the Global requirements such as


Problem Solving Skills, Cultural Sensitivity, Ethical behavior and Social
Responsibility.
2. To motivate our Students to pursue Higher Education and engage in
continuous upgradation of their Professional Skills.
3. To encourage students to develop Communication Skills, Professional
Values and Positive Attitude that in turn leads to fostering Leadership
Qualities.
PROGRAM OUTCOMES (POs)

Engineering Graduates will be able to:

1. Engineering Knowledge: Apply knowledge of mathematics, natural science, computing, engineering


fundamentals and an engineering specialization as specified in WK1 to WK4 respectively to develop to the
solution of complex engineering problems.
2. Problem Analysis: Identify, formulate, review research literature and analyze complex engineering
problems reaching substantiated conclusions with consideration for sustainable development. (WK1 to
WK4).
3. Design/Development of Solutions: Design creative solutions for complex engineering problems and
design/develop systems/components/processes to meet identified needs with consideration for the public
health and safety, whole-life cost, net zero carbon, culture, society and environment as required. (WK5).
4. Conduct Investigations of Complex Problems: Conduct investigations of complex engineering
problems using research-based knowledge including design of experiments, modelling, analysis &
interpretation of data to provide valid conclusions. (WK8).
5. Engineering Tool Usage: Create, select and apply appropriate techniques, resources and modern
engineering & IT tools, including prediction and modelling recognizing their limitations to solve complex
engineering problems. (WK2 and WK6).
6. The Engineer and The World: Analyze and evaluate societal and environmental aspects while solving
complex engineering problems for its impact on sustainability with reference to economy, health, safety,
legal framework, culture and environment. (WK1, WK5, and WK7).
7. Ethics: Apply ethical principles and commit to professional ethics, human values, diversity and inclusion;
adhere to national & international laws. (WK9).
8. Individual and Collaborative Team work: Function effectively as an individual, and as a member or
leader in diverse/multi-disciplinary teams.
9. Communication: Communicate effectively and inclusively within the engineering community and
society at large, such as being able to comprehend and write effective reports and design documentation,
make effective presentations considering cultural, language, and learning differences.
10. Project Management and Finance: Apply knowledge and understanding of engineering management
principles and economic decision-making and apply these to one’s own work, as a member and leader in a
team, and to manage projects and in multidisciplinary environments.
11. Life-Long Learning: Recognize the need for, and have the preparation and ability for i) independent
and life-long learning ii) adaptability to new and emerging technologies and iii) critical thinking in the
broadest context of technological change. (WK8)
COURSE LEARNING OBJECTIVES (CLO)

CLO1. Learn the syntax and semantics of the Python programming language.
CLO2. Illustrate the process of structuring the data using lists, tuples.
CLO3. Demonstrate the use of built-in functions to navigate the file system.
CLO4. Implement the Object Oriented Programming concepts in Python.
CLO5. Appraise the need for working with various documents like Excel, PDF, Word and Others.

COURSE OUTCOMES (CO)

At the end of the course the student will be able to:


CO1. Understand the basic syntax, keywords, and core concepts of Python programming,
including datatypes, operators, and control structures.
CO2. Apply Python programming techniques to structure data using lists, tuples, and dictionaries
for effective data management.
CO3. Analyze and implement file operations in Python, including reading, writing, and navigating
through different file systems using built-in functions.
CO4. Implement object-oriented programming (OOP) principles in Python to design and develop classes,
objects, and methods for modular programming.
CO5. Demonstrate the ability to apply Python programming techniques to solve real-world problems.

CO TO PO & PSO MAPPING 1/2/3

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11

CO1 3 2 2

CO2 3 3 2
BPLCK205B

CO3 3 2 3

CO4 3 2 3

CO5 3 3 2 2
Introduction to Python Programming Laboratory

Subject Code: BPLCK205B I.A. Marks: 25


Hours/Week: 02 Total Hours: 24
LIST OF PROGRAMS

Sl. Name of Experiment


No.

1. a. Develop a program to read the student details like Name, USN, and Marks in three
subjects. Display the student details, total marks and percentage with suitable messages.
b. Develop a program to read the name and year of birth of a person. Display whether the
person is a senior citizen or not.

2. Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages.
3. Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable message.
4. Develop a program to print 10 most frequently appearing words in a text file. [Hint: Use
dictionary with distinct words and their frequency of occurrences. Sort the dictionary in the
reverse order of frequency and display dictionary slice of first 10 items]
5. Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file. [Hint: Use string methods strip(), len(), list methods sort(), append(), and
file methods open(), readlines(), and write()].
6. Develop a program to backing Up a given Folder (Folder in a current working directory)
into a ZIP File by using relevant modules and suitable methods.
7. Write a function named DivExp which takes TWO parameters a, b and returns a value c
(c=a/b). Write suitable assertion for a>0 in function DivExp and raise an exception for when
b=0. Develop a suitable program which reads two values from the console and calls a
function DivExp.
8. Define a function which takes TWO objects representing complex numbers and returns new
complex number with a addition of two complex numbers. Define a suitable class
‘Complex’ to represent the complex number. Develop a program to read N (N >=2)
complex numbers and to compute the addition of N complex numbers.
9. Develop a program that uses class Student which prompts the user to enter marks in three
subjects and calculates total marks, percentage and displays the score card details. [Hint:
Use list to store the marks in three subjects and total marks. Use _init_() method to initialize
name, USN and the lists to store marks and total, Use getMarks() method to read marks
into the list, and display() method to display the score card details.]
10. a. Write a python program to download the all XKCD comics
b. Demonstrate python program to read the data from the spreadsheet and write the data in
to the spreadsheet.
BPLCK205B Introduction to Python Programming Laboratory

Python Programming Laboratory

Subject Code: BPLCK205B I.A. Marks: 25


Hours/Week: 02 Total Hours: 24

SCHEDULE OF EXPERIMENTS

Sl. No Name of Experiment WEEK


1 Sample programs Week1
2 Sample programs Week2
3 Student Details, Senior Citizen Check Week3
4 Mean, Variance and Standard Deviation Week4
5 Digit Frequency Week5
6 Word Frequency Week6
7 Sort File Contents Week7
8 Backup Directory into Zip Week8
9 Assertions and Exceptions Demo Week9
10 Complex Class Demo Week10
11 Student Class Demo Week11
12 Download XKCD comics, Read and Write data to Week12
spreadsheet.

BIT, Bengaluru-04 Page 1


BPLCK205B Introduction to Python Programming Laboratory

LABORATORY
General Lab Guidelines:
1. Conduct yourself in a responsible manner at all times in the laboratory. Intentional
misconduct will lead to exclusion from the lab.
2. Do not wander around, or distract other students, or interfere with the laboratory
experiments of other students.
3. Read the handout and procedures before starting the experiments. Follow all written
and verbal instructions carefully.
4. If you do not understand the procedures, ask the instructor or teaching assistant.
Attendance in all the labs is mandatory, absence permitted only with prior permission
from the Class teacher.
5. The workplace has to be tidy before, during and after the experiment.
6. Do not eat food, drink beverages or chew gum in the laboratory.
7. Every student should know the location and operating procedures of all Safety
equipment including First Aid Kit and Fire extinguisher.

DO’S:-
1. An ID card is a must.
2. Keep your belongings in a designated area.
3. Sign the log book when you enter/leave the laboratory.
4. Records have to be submitted every week for evaluation.
5. The program to be executed in the respective lab session has to be written in the lab
observation copy beforehand.
6. After the lab session, shut down the computers.
7. Report any problem in system (if any) to the person in-charge

DON'TS:-
1. Do not insert metal objects such as clips, pins and needles into the computer
casings(They may cause fire) and should not attempt to repair, open, tamper or interfere
with any of the computer, printing, cabling, or other equipment in the laboratory.
2. Do not change the system settings and keyboard keys.
3. Do not upload, delete or alter any software/ system files on laboratory computers.
4. No additional material should be carried by the students during regular labs.
5. Do not open any irrelevant websites in labs.

BIT, Bengaluru-04 Page 2


BPLCK205B Introduction to Python Programming Laboratory

6. Do not use a flash drive on lab computers without the consent of the lab instructor.
7. Students are not allowed to work in the Laboratory alone or without the presence of the
instructor/teaching assistant.

BIT, Bengaluru-04 Page 3


BPLCK205B Introduction to Python Programming Laboratory

PYTHON PROGRAMMING

Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

What can Python do?

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software
development.

Why Python?

 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than
some other programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it
is written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional
way.

Python Install

To check if you have python installed on a Windows PC, search in the start bar for Python or
run the following on the Command Line (cmd.exe):

BIT, Bengaluru-04 Page 4


BPLCK205B Introduction to Python Programming Laboratory

C:\Users\Your Name>python --version

To check if you have python installed on a Linux or Mac, then on linux open the command
line or on Mac open the Terminal and type:

python --version

Python Syntax

Python syntax can be executed by writing directly in the Command Line:

>>> print("Hello, World!")


Hello, World!

Or by creating a python file on the server, using the .py file extension, and running it in the
Command Line:

C:\Users\Your Name>python myfile.py

Python Indentation

Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.

Python uses indentation to indicate a block of code.

if 5 > 2:
print("Five is greater than two!")

Python Comments

 Comments can be used to explain Python code.

 Comments can be used to make the code more readable.

 Comments can be used to prevent execution when testing code.

BIT, Bengaluru-04 Page 5


BPLCK205B Introduction to Python Programming Laboratory

 Creating a Comment

Comments starts with a #, and Python will ignore them:

#This is a comment
print("Hello, World!")

Multiline Comments

Python does not really have a syntax for multiline comments.

To add a multiline comment you could insert a # for each line:

#This is a comment
#written in
#more than just one line
print("Hello, World!")

Python Variables

Variables are containers for storing data values.

Creating Variables

Python has no command for declaring a variable.

A variable is created the moment you first assign a value to it.

x=5
y = "John"
print(x)
print(y)

Python Data Types

Built-in Data Types

In programming, data type is an important concept.

BIT, Bengaluru-04 Page 6


BPLCK205B Introduction to Python Programming Laboratory

Variables can store data of different types, and different types can do different things.

Python has the following data types built-in by default, in these categories:

Text Type: Str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: Dict

Set Types: set, frozenset

Boolean Type: Bool

Binary Types: bytes, bytearray, memoryview

None Type: NoneType

Python Strings

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

'hello' is the same as "hello".

Python Booleans

Booleans represent one of two values: True or False.

Boolean Values

In programming you often need to know if an expression is True or False.

You can evaluate any expression in Python, and get one of two answers, True or False.

BIT, Bengaluru-04 Page 7


BPLCK205B Introduction to Python Programming Laboratory

print(10 > 9)
print(10 == 9)
print(10 < 9)

Python Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

print(10 + 5)

Python divides the operators in the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Identity operators
 Membership operators
 Bitwise operators

Python Lists

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, the other 3
are Tuple, Set, and Dictionary, all with different qualities and usage.

thislist = ["apple", "banana", "cherry"]


print(thislist)

Python If ... Else

Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b

BIT, Bengaluru-04 Page 8


BPLCK205B Introduction to Python Programming Laboratory

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

Python Loops

Python has two primitive loop commands:

 while loops
 for loops

while Loop

With the while loop we can execute a set of statements as long as a condition is true.

i=1
while i < 6:
print(i)
i += 1

For Loops

A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string).

This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.

With the for loop we can execute a set of statements, once for each item in a list, tuple, set
etc.

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

BIT, Bengaluru-04 Page 9


BPLCK205B Introduction to Python Programming Laboratory

SAMPLE PROGRAMS

1. Python Program to Print Hello world!

print ('Hello Python')


2. Python Program to Add Two Numbers

x=4

y=3

print (x + y)

3. Python Program to Find the Square Root

num = float (input ('Enter a number: '))

num_sqrt = num ** 0.5

print ('The square root of %0.3f is %0.3f' % (num ,num_sqrt))

4. Python Program to Find the Sum of Natural Numbers


# Sum of natural numbers up to num
num = 16
if num < 0:
print("Enter a positive number")
else:
sum = 0
# use while loop to iterate until zero
while(num > 0):
sum += num
num -= 1
print("The sum is", sum)

BIT, Bengaluru-04 Page 10


BPLCK205B Introduction to Python Programming Laboratory

5. Python Program to Check Armstrong Number

# take input from the user


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

# initialize sum
sum = 0

# find the sum of the cube of each digit


temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10

# display the result


if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")

BIT, Bengaluru-04 Page 11


BPLCK205B Introduction to Python Programming Laboratory

LAB PROGRAMS

PROGRAM 1
A. Develop a program to read the student details like Name, USN, and Marks in
three subjects. Display the student details, total marks and percentage with
suitable messages.

stName = input("Enter the name of the student : ")


stUSN = input("Enter the USN of the student : ")
MaxMarks1= int(input("Enter Max marks in Subject 1 : "))
MaxMarks2=int(input("Enter Max marks in Subject 2 : "))
MaxMarks3=int(input("Enter Max marks in Subject 3 : "))
stMarks1 = int(input("Enter marks in Subject 1 : "))
stMarks2 = int(input("Enter marks in Subject 2 : "))
stMarks3 = int(input("Enter marks in Subject 3 : "))
print("Student Details\n=========================")
print ("Name :", stName)
print("USN :", stUSN)
print("Marks 1 :", stMarks1)
print("Marks 2 :", stMarks2)
print("Marks 3 :", stMarks3)
print("Total :", stMarks1+stMarks2+stMarks3)
print("Percent :",(stMarks1+stMarks2+stMarks3)/3)
print("=========================")

Output
Enter the name of the student : abc
Enter the USN of the student : 1234
Enter Max marks in Subject 1 : 100
Enter Max marks in Subject 2 : 100
Enter Max marks in Subject 3 : 100
Enter marks in Subject 1 : 90
Enter marks in Subject 2 : 98
Enter marks in Subject 3 : 97

BIT, Bengaluru-04 Page 12


BPLCK205B Introduction to Python Programming Laboratory

Student Details
=========================
Name : abc
USN : 1234
Marks 1 : 90
Marks 2 : 98
Marks 3 : 97
Total : 285
Percent : 95.0
=========================

BIT, Bengaluru-04 Page 13


BPLCK205B Introduction to Python Programming Laboratory

B. Develop a program to read the name and year of birth of a person. Display
whether the person is a senior citizen or not.

perName = input("Enter the name of the person : ")


perDOB = int(input("Enter his year of birth : "))
curyear=int(input("Enter the current year:"))
perAge = curyear - perDOB
if (perAge > 60):
print(perName, "aged", perAge, "years is a Senior Citizen.")
else:
print(perName, "aged", perAge, "years is not a Senior Citizen.")

Output

=================================

Enter the name of the person : Akbar Khan

Enter his year of birth : 1994

Enter the current year:2023

Akbar Khan aged 29 years is not a Senior Citizen.

Enter the name of the person : George Best

Enter his year of birth : 1957

Enter the current year:2023

George Best aged 66 years is a Senior Citizen.

BIT, Bengaluru-04 Page 14


BPLCK205B Introduction to Python Programming Laboratory

PROGRAM 2
Read N numbers from the console and create a list. Develop a program to print mean,
variance, and standard deviation with suitable messages.

from math import sqrt


myList = []
num = int(input("Enter the number of elements in your list : "))
for i in range(num):
val = int(input("Enter the element : "))
myList.append(val)
print('The length of list1 is', len(myList))
print('List Contents', myList)
total = 0
for elem in myList:
total += elem
mean = total / num
total = 0
for elem in myList:
total += (elem - mean) * (elem - mean)
variance = total / numstdDev = sqrt(variance)
print("Mean =", mean)
print("Variance =", variance)
print("Standard Deviation =", stdDev)

Output

Enter the number of elements in your list : 5


Enter the element : 45
Enter the element : 34
Enter the element : 86
Enter the element : 92
Enter the element : 35

The length of list1 is 5

BIT, Bengaluru-04 Page 15


BPLCK205B Introduction to Python Programming Laboratory

List Contents [45, 34, 86, 92, 35]

Mean = 58.4
Variance = 642.64
Standard Deviation = 25.35

BIT, Bengaluru-04 Page 16


BPLCK205B Introduction to Python Programming Laboratory

PROGRAM 3
Read a multi-digit number (as chars) from the console. Develop a program to print the
frequency of each digit with suitable message.

num = input("Enter a number : ")


print("The number entered is :", num)
uniqDig = set(num)
for elem in uniqDig:
print(elem, "occurs", num.count(elem), "times")

Output
Enter a number : 234939
The number entered is : 234939
4 occurs 1 times
9 occurs 2 times
3 occurs 2 times
2 occurs 1 times

Enter a number : 7843338


The number entered is : 7843338
7 occurs 1 times
4 occurs 1 times
3 occurs 3 times
8 occurs 2 times

BIT, Bengaluru-04 Page 17


BPLCK205B Introduction to Python Programming Laboratory

PROGRAM 4
Develop a program to print 10 most frequently appearing words in a text file. [Hint: Use
dictionary with distinct words and their frequency of occurrences. Sort the dictionary in
the reverse order of frequency and display dictionary slice of first 10 items].

ifile= open("python.txt")
dict_words={}
for line in ifile:
words = line.split()
for word in words:
dict_words[word]=dict_words.get(word,0)+1
list_words=[]
for key,val in dict_words.items():
list_words.append((val,key))
list_words.sort(reverse=True)
print("The slice of visit 10 items of sorted dictionary are:")
print(list_words[0:10])

Output
Enter the filename : python.txt

===================================================
10 most frequently appearing words with their count
===================================================
the occurs 45 times
of occurs 24 times
party occurs 12 times
part occurs 12 times
a occurs 9 times
and occurs 8 times
second occurs 7 times
to occurs 6 times
shall occurs 6 times
first occurs 5 times

BIT, Bengaluru-04 Page 18


BPLCK205B Introduction to Python Programming Laboratory

PROGRAM 5
Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file. [Hint: Use string methods strip(), len(), list methods sort(), append(), and
file methods open(), readlines(), and write()].

import os.path
import sys
fname = input("Enter the filename whose contents are to be sorted : ") #sample
file unsorted.txt also provided
if not os.path.isfile(fname):
print("File", fname, "doesn’t exists")
sys.exit(0)
infile = open(fname, "r")
myList = infile.readlines()
# print(myList)

#Remove trailing \n characters


lineList = []
for line in myList:
lineList.append(line.strip())
lineList.sort()
#Write sorted contents to new file sorted.txt
outfile = open("sorted.txt","w")
for line in lineList:
outfile.write(line + "\n")
infile.close() # Close the input file
outfile.close() # Close the output file
if os.path.isfile("sorted.txt"):
print("\nFile containing sorted content sorted.txt created successfully")
print("sorted.txt contains", len(lineList), "lines")
print("Contents of sorted.txt")
print("=============================================================
====")
rdFile = open("sorted.txt","r")

BIT, Bengaluru-04 Page 19


BPLCK205B Introduction to Python Programming Laboratory

for line in rdFile:


print(line, end="")

Output
Enter the filename whose contents are to be sorted : unsorted.txt

File containing sorted content sorted.txt created successfully


sorted.txt contains 15 lines
Contents of sorted.txt
=================================================================
A deep C diva.
All the troubles you have will pass away very quickly.
Beware of a tall black man with one blond shoe.
Don’t read everything you believe.
Exercise caution in your daily affairs.
He changes the domain.
How does a hacker fix a function which doesn’t work for all of the elements in its
domain?
Lay on, MacDuff, and curs’d be him who first cries, "Hold, enough!".
People are beginning to notice you. Try dressing before you leave the house.
The surest protection against temptation is cowardice.
To be or not to be.
Tuesday is the Wednesday of the rest of your life.
What is the square root of 4bˆ2?
You display the wonderful traits of charm and courtesy.
You may be recognized soon. Hide.

BIT, Bengaluru-04 Page 20


BPLCK205B Introduction to Python Programming Laboratory

PROGRAM 6
Develop a program to backing Up a given Folder (Folder in a current working
directory) into a ZIP File by using relevant modules and suitable methods.

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

BIT, Bengaluru-04 Page 21


BPLCK205B Introduction to Python Programming Laboratory

PROGRAM 7
Write a function named DivExp which takes TWO parameters a, b and returns a
value c (c=a/b). Write suitable assertion for a greater than 0 in function DivExp and
raise an exception for when b=0. Develop a suitable program which reads two values
from the console and calls a function DivExp.

import sys
def DivExp(a,b):
assert a>0, "a should be greater than 0"
try:
c = a/b
except ZeroDivisionError:
print("Value of b cannot be zero")
sys.exit(0)
else:
return c
val1 = int(input("Enter a value for a : "))
val2 = int(input("Enter a value for b : "))
val3 = DivExp(val1, val2)
print(val1, "/", val2, "=", val3)

OUTPUT
Enter a value for a : 7
Enter a value for b : 6
7 / 6 = 1.1666666666666667

Enter a value for a : 0


Enter a value for b : 5
AssertionError: a should be greater than 0

Enter a value for a : -3


Enter a value for b : 6
AssertionError: a should be greater than 0

BIT, Bengaluru-04 Page 22


BPLCK205B Introduction to Python Programming Laboratory

Enter a value for a : 6


Enter a value for b : 0
Value of b cannot be zero

BIT, Bengaluru-04 Page 23


BPLCK205B Introduction to Python Programming Laboratory

PROGRAM 8
Define a function which takes 2 objects representing complex numbers and returns new
complex number with a addition of two complex numbers. Define a suitable class Complex
to represent the complex number. Develop a program to read N (N greater than 2)
complex numbers and to compute the addition of N complex numbers.

class Complex:
def init (self, realp = 0, imagp=0):
self.realp = realp
self.imagp = imagp
def setComplex(self, realp, imagp):
self.realp = realp
self.imagp = imagp
def readComplex(self):
self.realp = int(input("Enter the real part : "))
self.imagp = int(input("Enter the real part : "))
def showComplex(self):
print('(',self.realp,')','+i','(',self.imagp,')',sep="")
def addComplex(self, c2):
c3 = Complex()
c3.realp = self.realp + c2.realp
c3.imagp = self.imagp + c2.imagp
return c3
def add2Complex(a,b):
c = a.addComplex(b)
return c
def main():
c1 = Complex(3,5)
c2 = Complex(6,4)
print("Complex Number 1")
c1.showComplex()
print("Complex Number 2")
c2.showComplex()
c3 = add2Complex(c1, c2)

BIT, Bengaluru-04 Page 24


BPLCK205B Introduction to Python Programming Laboratory

print("Sum of two Complex Numbers")


c3.showComplex()
compList = []
num = int(input("\nEnter the value for N : "))

for i in range(num):
print("Object", i+1)
obj = Complex()
obj.readComplex()
compList.append(obj)
print("\nEntered Complex numbers are : ")
for obj in compList:
obj.showComplex()
sumObj = Complex()
for obj in compList:
sumObj = add2Complex(sumObj, obj)
print("\nSum of N complex numbers is", end = " ")
sumObj.showComplex()
main()

Output
Complex Number 1
(3)+i(5)
Complex Number 2
(6)+i(4)
Sum of two Complex Numbers
(9)+i(9)

Enter the value for N : 5


Object 1
Enter the real part : 1
Enter the real part : 9
Object 2
Enter the real part : 2

BIT, Bengaluru-04 Page 25


BPLCK205B Introduction to Python Programming Laboratory

Enter the real part : 8


Object 3
Enter the real part : 3
Enter the real part : 7
Object 4
Enter the real part : 4
Enter the real part : 6
Object 5
Enter the real part : 5
Enter the real part : 5

Entered Complex numbers are :


(1)+i(9)
(2) +i(8)
(3) +i(7)
(4) +i(6)
(5) +i(5)

Sum of N complex numbers is (15)+i(35)

BIT, Bengaluru-04 Page 26


BPLCK205B Introduction to Python Programming Laboratory

PROGRAM 9
Develop a program that uses class Student which prompts the user to enter marks in
three subjects and calculates total marks, percentage and displays the score card details.
[Hint: Use list to store the marks in three subjects and total marks. Use init method to
initialize name, USN and the lists to store marks and total, Use getMarks() method to
read marks into the list, and display() method to display the score card details.]

class Student:
def init (self, name = "", usn = "", score = [0,0,0,0]):
self.name = name
self.usn = usn
self.score = score
def getMarks(self):
self.name = input("Enter student Name : ")
self.usn = input("Enter student USN : ")
self.score[0] = int(input("Enter marks in Subject 1 : "))
self.score[1] = int(input("Enter marks in Subject 2 : "))
self.score[2] = int(input("Enter marks in Subject 3 : "))
self.score[3] = self.score[0] + self.score[1] + self.score[2]
def display(self):
percentage = self.score[3]/3
spcstr = "=" * 81
print(spcstr)
print("SCORE CARD DETAILS".center(81))
print(spcstr)
print("NAME","USN","MARKS1","MARKS2","MARKS3","TOTAL",
"PERCENTAGE")
print(spcstr)
print("%15s"%self.name, "%12s"%self.usn,"%8d"%self.score[0],
"%8d"%self.score[1],"%8d"%self.score[2], "%8d"%self.score[3],
"%12.2f"%percentage)
print(spcstr)

BIT, Bengaluru-04 Page 27


BPLCK205B Introduction to Python Programming Laboratory

def main():
s1 = Student()
s1.getMarks()
s1.display()
main()

Output
Enter student Name : vi
Enter student USN : 123
Enter marks in Subject 1 : 23
Enter marks in Subject 2 : 22
Enter marks in Subject 3 : 24
=================================================================
================
SCORE CARD DETAILS
=================================================================
================
NAME USN MARKS1 MARKS2 MARKS3 TOTAL PERCENTAGE
=================================================================
================
vi 123 23 22 24 69 23.00

BIT, Bengaluru-04 Page 28


BPLCK205B Introduction to Python Programming Laboratory

PROGRAM 10
A. Write a python program to download the all XKCD
comics

#! python3
# downloadXkcd.py - Downloads every single XKCD comic.
import requests, os, bs4
import urllib3
flag = 'y'
url = 'http://xkcd.com' # starting url
os.makedirs('xkcd2', exist_ok=True) # store comics in ./xkcd
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text,'html.parser')
prevLink = soup.select('a[rel="prev"]')[0]
img_no = int(((prevLink.get('href')).split('/'))[1])+1
print("Total images there are", img_no)
while (flag == 'y' or flag == 'Y'):
print("Enter the number between 1 and",img_no)
url_img_no = input()
url = 'http://xkcd.com'
url = url + '/' + url_img_no
res = requests.get(url)
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text,'html.parser')
comicElem = soup.select('#comic img')
if comicElem == []:
print('Could not find comic image.')
else:
comicUrl = 'http:' + comicElem[0].get('src')
# Download the image.
print('Downloading image %s...' % (comicUrl))
res = requests.get(comicUrl)
res.raise_for_status()
# Save the image to ./xkcd.
imageFile = open(os.path.join('xkcd2', os.path.basename(comicUrl)), 'wb')
BIT, Bengaluru-04 Page 29
BPLCK205B Introduction to Python Programming Laboratory

for chunk in res.iter_content(100000):


imageFile.write(chunk)
imageFile.close()
flag = input("Enter y to continue")

Output
Total images there are 3072
Enter the number between 1 and 3072
356
Downloading image http://imgs.xkcd.com/comics/nerd_sniping.png...
Enter y to continue y
Enter the number between 1 and 3072
679
Downloading image http://imgs.xkcd.com/comics/christmas_plans.png...
Enter y to continue

xkcd2 folder gets created with the images downloaded in it

BIT, Bengaluru-04 Page 30


BPLCK205B Introduction to Python Programming Laboratory

B. Demonstrate python program to read the data from the spreadsheet and write the data
in to 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"
sheet.cell(row = 1, column = 4).value = "capital"

ft = Font(bold=True)
for row in sheet["A1:D1"]:
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]
sheet.cell(row = i, column = 4).value = capital[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 = 4).value)
sheet = wb["Language"]

BIT, Bengaluru-04 Page 31


BPLCK205B Introduction to Python Programming Laboratory

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)
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

demo.xlsx gets created

BIT, Bengaluru-04 Page 32


INTRODUCTION TO PYTHON PROGRAMMING – BPLCK205B

INTRODUCTION TO PYTHON PROGRMMING - BPLCK205B


Case Study Python Programs as per NEP SCHEME

1) Develop a python program to calculate the area of rectangle and triangle.


Print the results.

# Calculate the area of a rectangle


length = float(input("Enter the length of the rectangle: "))
width = float(input("Enter the width of the rectangle: "))
rectangle_area = length * width
print("The area of the rectangle is:", rectangle_area)

# Calculate the area of a triangle


base = float(input("Enter the base length of the triangle: "))
height = float(input("Enter the height of the triangle: "))
triangle_area = 0.5 * base * height
print("The area of the triangle is:", triangle_area)

2) Develop a python program to check whether given year is a leap year or


not
import datetime
import calendar

year = int(input("Enter a year: "))

if calendar.isleap(year):
print(year, "is a leap year.")
else:
print(year, "is not a leap year.")

1
INTRODUCTION TO PYTHON PROGRAMMING – BPLCK205B

3) a) Develop a python program to check prime number using functions

def is_prime(number):
if number <= 1:
return False
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True

# Take user input


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

# Check if the number is prime


if is_prime(num):
print(num, "is a prime number.")
else:
print(num, "is not a prime number.")

3) b) Develop a python program to display prime number between 10 & 100


def is_prime(number):
if number <= 1:
return False
for i in range(2, int(number ** 0.5) + 1):
if number % i == 0:
return False
return True

# Define the range


start = 10
end = 100

2
INTRODUCTION TO PYTHON PROGRAMMING – BPLCK205B

# Find and display prime numbers in the range


print("Prime numbers between", start, "and", end, "are:")
for num in range(start, end + 1):
if is_prime(num):
print(num)

4) Develop a python program to check whether given number is even, odd,


positive & negative
num = float(input("Enter a number: "))

# Check if the number is even or odd


if num % 2 == 0:
print(num, "is an even number.")
else:
print(num, "is an odd number.")

# Check if the number is positive or negative


if num > 0:
print(num, "is a positive number.")
elif num < 0:
print(num, "is a negative number.")
else:
print("The number is zero.")

3
INTRODUCTION TO PYTHON PROGRAMMING – BPLCK205B

5) Develop a python program to find sum of first “n” natural numbers


n = int(input("Enter a positive integer 'n': "))
# Check if the input is a positive integer
if n <= 0:
print("Invalid input. Please enter a positive integer.")
else:
sum_of_numbers = (n * (n + 1)) // 2
print("The sum of the first", n, "natural numbers is:", sum_of_numbers)

6) Develop a python program to find sum & average of all the elements in list
# Function to calculate sum of list elements
def calculate_sum(numbers):
total_sum = sum(numbers)
return total_sum

# Function to calculate average of list elements


def calculate_average(numbers):
total_sum = calculate_sum(numbers)
average = total_sum / len(numbers)
return average

# Main program
num_list = []
n = int(input("Enter the number of elements in the list: "))
# Input list elements
for i in range(n):
num = float(input("Enter element {}: ".format(i+1)))
num_list.append(num)

4
INTRODUCTION TO PYTHON PROGRAMMING – BPLCK205B

# Calculate sum and average


sum_of_elements = calculate_sum(num_list)
average_of_elements = calculate_average(num_list)

# Print the results


print("Sum of elements:", sum_of_elements)
print("Average of elements:", average_of_elements)

7) Develop a python program to sort ascending & descending, display length


of the list
# Function to sort the list in ascending order
def sort_ascending(numbers):
sorted_list = sorted(numbers)
return sorted_list

# Function to sort the list in descending order


def sort_descending(numbers):
sorted_list = sorted(numbers, reverse=True)
return sorted_list

# Main program
num_list = []
n = int(input("Enter the number of elements in the list: "))

# Input list elements


for i in range(n):
num = float(input("Enter element {}: ".format(i+1)))
num_list.append(num)

# Sort the list in ascending and descending order


ascending_list = sort_ascending(num_list)
5
INTRODUCTION TO PYTHON PROGRAMMING – BPLCK205B

descending_list = sort_descending(num_list)

# Display the sorted lists


print("Ascending order:", ascending_list)
print("Descending order:", descending_list)

# Display the length of the list


list_length = len(num_list)
print("Length of the list:", list_length)

8) Develop a python program to find smallest & largest value in a list


# Function to find the smallest value in a list
def find_smallest(numbers):
smallest = min(numbers)
return smallest

# Function to find the largest value in a list


def find_largest(numbers):
largest = max(numbers)
return largest

# Main program
num_list = []
n = int(input("Enter the number of elements in the list: "))

# Input list elements


for i in range(n):
num = float(input("Enter element {}: ".format(i+1)))
num_list.append(num)

6
INTRODUCTION TO PYTHON PROGRAMMING – BPLCK205B

# Find the smallest and largest values


smallest_value = find_smallest(num_list)
largest_value = find_largest(num_list)

# Print the results


print("Smallest value in the list:", smallest_value)
print("Largest value in the list:", largest_value)

9) Develop a python program to sort by value or key


# List of dictionaries
data = [
{"name": "Alice", "age": 25, "score": 90},
{"name": "Bob", "age": 20, "score": 85},
{"name": "Charlie", "age": 30, "score": 95},
{"name": "David", "age": 22, "score": 88},
]

# Function to sort by value


def sort_by_value(item):
return item["value"]

# Function to sort by key


def sort_by_key(item):
return item["key"]

# Sort by value
sorted_by_value = sorted(data, key=sort_by_value)

# Sort by key
sorted_by_key = sorted(data, key=sort_by_key)

7
INTRODUCTION TO PYTHON PROGRAMMING – BPLCK205B

# Print the sorted lists


print("Sorted by value:")
for item in sorted_by_value:
print(item)

print("\nSorted by key:")
for item in sorted_by_key:
print(item)

10) Develop a python program to map two lists into a dictionary


keys = ["name", "age", "country"]
values = ["Alice", 25, "USA"]

# Create a dictionary by mapping the two lists


mapped_dict = dict(zip(keys, values))

# Print the resulting dictionary


print(mapped_dict)

11) Develop a python program to append text to a file and display the text
# Function to append text to a file
def append_to_file(filename, text):
with open(filename, 'a') as file:
file.write(text)
print("Text appended to the file successfully.")

# Function to read and display the contents of a file


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

8
INTRODUCTION TO PYTHON PROGRAMMING – BPLCK205B

contents = file.read()
print("File contents:")
print(contents)

# Main program
filename = "sample.txt"
text_to_append = input("Enter the text to append to the file: ")

# Append text to the file


append_to_file(filename, text_to_append)

# Display the contents of the file


display_file_contents(filename)

12) Develop a python program to count the total number of upper case, lower
case & digits used in text file
def count_characters(filename):
uppercase_count = 0
lowercase_count = 0
digit_count = 0

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


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

9
INTRODUCTION TO PYTHON PROGRAMMING – BPLCK205B

return uppercase_count, lowercase_count, digit_count

filename = "sample.txt"

# Count the characters in the file


uppercase, lowercase, digits = count_characters(filename)

# Print the results


print("Total number of uppercase letters:", uppercase)
print("Total number of lowercase letters:", lowercase)
print("Total number of digits:", digits)

13) Develop a python program to demonstrate multiple exception handling


in python
def divide_numbers(num1, num2):
try:
result = num1 / num2
print("Result of division:", result)
except ZeroDivisionError:
print("Error: Division by zero is not allowed.")
except TypeError:
print("Error: Invalid data types for division.")
except Exception as e:
print("An error occurred:", str(e))

# Example usages
divide_numbers(10, 2) # Normal division
divide_numbers(10, 0) # Division by zero
divide_numbers(10, "2") # Invalid data types
divide_numbers(10) # Missing second argument

10
INTRODUCTION TO PYTHON PROGRAMMING – BPLCK205B

14) Develop a python program, define a class and object, construct the class
called rectangle and initialize it with height = 100, width = 200, starting point
as (x=0, y = 0). Write a program to display the centre point coordinates of a
rectangle.
class Rectangle:
def init (self, height, width, x, y):
self.height = height
self.width = width
self.x = x
self.y = y

def calculate_center_point(self):
center_x = self.x + (self.width / 2)
center_y = self.y + (self.height / 2)
return center_x, center_y

# Create an instance of the Rectangle class


rectangle = Rectangle(100, 200, 0, 0)

# Calculate and display the center point coordinates


center_x, center_y = rectangle.calculate_center_point()
print("Center point coordinates: ({}, {})".format(center_x, center_y))

15) Develop a python program for addition of two complex number’s by


operator loading binary plus operator (using magic method _ _add_ _ (self,
other). Include _ _ init_ _ & _ _ str _ _ functions
class ComplexNumber:
def init (self, real, imaginary):
self.real = real
self.imaginary = imaginary

11
INTRODUCTION TO PYTHON PROGRAMMING – BPLCK205B

def add (self, other):


if isinstance(other, ComplexNumber):
real_sum = self.real + other.real
imaginary_sum = self.imaginary + other.imaginary
return ComplexNumber(real_sum, imaginary_sum)
else:
raise TypeError("Unsupported operand type for +: 'ComplexNumber' and
'{}'".format(type(other). name ))

def str (self):


if self.imaginary >= 0:
return "{} + {}i".format(self.real, self.imaginary)
else:
return "{} - {}i".format(self.real, abs(self.imaginary))

# Create complex numbers


c1 = ComplexNumber(2, 3)
c2 = ComplexNumber(4, -5)

# Perform addition
result = c1 + c2

# Display the result


print("Result of addition:", result)

12

You might also like