EAST WEST INSTITUTE OF
TECHNOLOGY
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
INTRODUCTION TO PYTHON
PROGRAMMING (BPCLK105B)
1ST SEMESTER
LABORATORY MANUAL
Prepared By:
Mrs. Padmavathi S Ms.Pratyaksha S
Assistant Professor, ISE/AD Assistant Professor, ISE/AD
APPROVED BY
Dr.Suresh M.B Dr. K. Channakeshavalu
Professor & Head, Principal & Director
Dept. of ISE, EWIT EWIT, Bangalore.
Name: ………..………………………………………………………………
USN: ……………………………. Branch: ………….……………………..
Section: ……………..…………… Batch: ……………….…………..
TABLE OF CONTENTS
Sl No. PARTICULARS
1 COURSE DETAILS
COURSE OBJECTIVES
SYLLABUS
COURSE OUTCOMES
2 EVALUATION PROCESS
Lab Programs:
PYTHON PROGRAMS
1(a) Develop a program to read the student details
1(b) Develop a program to read the name and year of birth of a person
2 Develop a program to generate Fibonacci sequence
3 Develop a program to print mean, variance and standard deviation
4 Develop a program to print the frequency of each digit
5 Develop a program to print 10 most frequently appearing words in a text file
6 Develop a program to sort the contents of a text file and write the sorted contents into a
separate text file
7 Develop a program to backing Up a given into a ZIP File by using relevant modules and
suitable methods.
8 Develop a suitable program which reads two values from the console and calls a function
DivExp.
9 Develop a program to read N (N >=2) complex numbers and to compute the addition of N
complex numbers.
10 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
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
COURSE DETAILS
Course Name: - Introduction to Python Programming
Course Code: - BPCLK105B
Course Prerequisite: - Core Java
Course Objectives
Learn the syntax and semantics of the Python programming language.
Illustrate the process of structuring the data using lists, tuples
Appraise the need for working with various documents like Excel, PDF, Word and
Others.
Demonstrate the use of built-in functions to navigate the file system.
Implement the Object Oriented Programming concepts in Python.
DEPT. OF ISE, EWIT Page 3
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
PYTHON PROGRAMS
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.
name = input("Enter the name of Student:")
usn = input("Enter the USN of Student:")
print("Enter the marks of three subjects::")
subject_1 = int(input ())
subject_2 = int (input ())
subject_3 = int (input ())
total = subject_1 + subject_2 + subject_3
percentage = (total / 300.0) * 100
print ("Name: ", name)
print ("USN: ", usn)
print ("The Total marks is: ", total)
print ("The Percentage is: ", percentage, "%")
Output :
Enter the name of Student: rashmi
Enter the USN of Student: 1ew21is001
Enter the marks of three subjects::
90
90
90
name: rashmi
USN: 1ew21is001
The Total marks is: 270.0
The Percentage is: 90.0 %
(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.
name =input( "Enter the name of the person: " )
year = int(input( "Enter the year of birth of the person: " ))
y = 2022-year
DEPT. OF ISE, EWIT Page 4
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
if y >= 60:
print ( name+” is a senior citizen” )
else :
print ( name+” is not a senior citizen”
Output :
Output1:
Enter the name of the person: Rashmi
Enter the year of birth of the person: 1993
Rashmi is not a senior citizen
Output2:
Enter the name of the person: Alice
Enter the year of birth of the person: 1940
Alice is a senior citizen
( 2 ) Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
n = int(input("enter the value of n: "))
def fibonacci(n):
fib1=0
fib2=1
if n == 1:
print(fib1)
elif n == 2:
print(fib1,fib2)
else:
print(fib1)
print(fib2)
for i in range(n-1):
fib3=fib1+fib2
print(fib3)
fib1=fib2
fib2=fib3
DEPT. OF ISE, EWIT Page 5
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
fibonacci(n)
Output:
enter the value of n: 9
0 1 1 2 3 5 8 13 21 34
2 b. Write a function to calculate factorial of a number. Develop a program to compute binomial coefficient
(Given N and R).
# Python 3 program to find
# factorial of given number
def factorial(n):
if n < 0:
return 0
elif n == 0 or n == 1:
return 1
else:
fact = 1
while(n > 1):
fact *= n
n -= 1
return fact
def binomial(n, r):
return factorial(n) /(factorial(r)*factorial(n - r))
n = int(input("enter the values of n: "))
r= int(input("enter the values of r: "))
print("Factorial of",n,"is",factorial(n))
ncr= binomial(n,r)
print("binomial coefficient is ",ncr)
DEPT. OF ISE, EWIT Page 6
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
Output:
enter the values of n: 4
enter the values of r: 2
Factorial of 4 is 24
binomial coefficient is 6.0
3. Read N numbers from the console and create a list. Develop a program to print mean, variance and
Standard deviation with suitable messages.
import math
def mean(a):
sum1=0
for i in a:
sum1+=i
m=sum1/N
return m
def var(a,m):
dev = 0
for y in a:
dev+=(y-m)**2
variance = dev/N
deviation = math.sqrt(variance)
return deviation, variance
N= int(input("enter the N: "))
List =[]
for i in range(N):
x = int(input("enter the list value:"))
List.append(x)
average=mean(List)
std_dev, variance =var(List,average)
print("mean: ",average)
print("Dev: ",std_dev)
print("var:",variance)
DEPT. OF ISE, EWIT Page 7
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
Output:
enter the N: 3
enter the list value:5
enter the list value:6
enter the list value:7
mean: 6.0
Dev: 0.816496580927726
var: 0.6666666666666666
4. Read a multi-digit number (as chars) from the console. Develop a program to print the frequency
of each digit with suitable message.
# Open the file in read mode
text = open("sample.txt", "r")
# Create an empty dictionary
d = dict()
# Loop through each line of the file
for line in text:
# Remove the leading spaces and newline character
line = line.strip()
# Convert the characters in line to
# lowercase to avoid case mismatch
line = line.lower()
# Split the line into words
words = line.split(" ")
# Iterate over each word in line
for word in words:
# Check if the word is already in dictionary
if word in d:
# Increment count of word by 1
DEPT. OF ISE, EWIT Page 8
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
d[word] = d[word] + 1
else:
# Add the word to dictionary with count 1
d[word] = 1
# Print the contents of dictionary
for key in list(d.keys()):
print(key, ":", d[key])
Output:
mango : 3
banana : 3
apple : 3
pear : 2
grapes : 1
strawberry : 2
kiwi : 1
5. 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]
import operator
import itertools
import pprint
text =open(“p1.txt” , ”r”)
d = dict()
for line in text:
line = line.strip()
line = line.lower()
words = line.split(" ")
for word in words:
if word in d:
DEPT. OF ISE, EWIT Page 9
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
d[word] = d[word] + 1
else:
d[word] = 1
sorted_d = dict( sorted(d.items(), key=operator.itemgetter(1),reverse=True))
print('Dictionary in reverse order of frequency :')
pprint.pprint(sorted_d)
out = dict(itertools.islice(sorted_d.items(), 10))
print("'first 10 items are: ")
pprint.pprint(out)
Output :
Dictionary in reverse order of frequency :
{'alice': 6,
'apple': 9,
'bob': 6,
'c': 3,
'c++': 3,
'he': 3,
'hello': 9,
'hi': 6,
'join': 3,
'list': 3,
'pyhton': 3,
'tuple': 3,
'welcome': 6}
'first 10 items are:
{'alice': 6,
'apple': 9,
'bob': 6,
'he': 3,
'hello': 9,
'hi': 6,
'join': 3,
DEPT. OF ISE, EWIT Page 10
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
'list': 3,
'pyhton': 3,
'welcome': 6}
6. Develop a program to sort the contents of a text file and write the sorted contents into a separate textfile.
[Hint: Use string methods strip(), len(), list methods sort(), append(), and file methods open(),readlines(),
and write()].
f = open("5.txt","r")
data = f.readlines()
sorted_word = []
for line in data:
line = line.strip()
line = line.lower()
words = line.split(" ")
for i in words:
sorted_word.append(i)
sorted_word.sort()
f.close()
o = open("result2.txt","w")
for i in range(len(sorted_word)):
o.write(sorted_word[i])
o.write(" ")
o.close()
Output :-
DEPT. OF ISE, EWIT Page 11
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
7. Develop a program to backing up a given folder(Folder in a current working directory) into a ZIP file by
using relevent modules and suitable methods
import zipfile, os
def backupToZip(folder):
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1
print(f'Creating {zipFilename}...')
backupZip = zipfile.ZipFile(zipFilename, 'w')
for foldername, subfolders, filenames in os.walk(folder):
print(f'Adding files in {foldername}...')
backupZip.write(foldername)
for filename in filenames:
newBase = os.path.basename(folder) + '_'
if filename.startswith(newBase) and filename.endswith('.zip'):
continue # don't back up the backup ZIP files
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
backupToZip('C:\\Users\\EWITISE-16\\desktop\\python')
Output:
Creating python_1.zip...
Done.
DEPT. OF ISE, EWIT Page 12
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
8. Write a function named DivExp which takes two parameters a, b returns 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
def DivExp(a , b):
try:
assert a>0, "a value must be greater than 0"
if b==0:
raise Exception("cannot divide by zero")
else:
c = a/b
return c
except Exception as err:
print(err)
a = int(input("enter the value of a:"))
b = int(input("enter the value of b:"))
DivExp(a,b)
Output 1:
enter the value of a:5
enter the value of b:6
0.8333333333333334
Output 2:
enter the value of a:0
enter the value of b:5
a value must be greater than 0
Output 3:
enter the value of a:6
enter the value of b:0
cannot divide by zero
DEPT. OF ISE, EWIT Page 13
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
9. Define a function which takes TWO objects representing complex numbers and returns a 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.
# Python3 program to Add two complex numbers
# User Defined Complex class
class Complex:
# Constructor to accept
# real and imaginary part
def init (self, tempReal, tempImaginary):
self.real = tempReal;
self.imaginary = tempImaginary;
# Defining addComp() method
# for adding two complex number
def addComp(self, C1, C2):
# creating temporary variable
temp=Complex(0, 0)
# adding real part of complex numbers
temp.real = C1.real + C2.real;
# adding Imaginary part of complex numbers
temp.imaginary = C1.imaginary + C2.imaginary;
# returning the sum
return temp;
DEPT. OF ISE, EWIT Page 14
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
# Driver code
if name ==' main ':
# First Complex number
C1 = Complex(3, 2);
# printing first complex number
print("Complex number 1 :", C1.real, "+ i" + str(C1.imaginary))
# Second Complex number
C2 = Complex(9, 5);
# printing second complex number
print("Complex number 2 :", C2.real, "+ i" + str(C2.imaginary))
# for Storing the sum
C3 = Complex(0, 0)
# calling addComp() method
C3 = C3.addComp(C1, C2);
# printing the sum
print("Sum of complex number :", C3.real, "+ i"+ str(C3.imaginary))
Output
Complex number 1 : 3 + i2
Complex number 2 : 9 + i5
Sum of complex number : 12 + i7
DEPT. OF ISE, EWIT Page 15
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
10. Develop a program that uses class Student which prompts the user to enter marks in three subjects
andcalculates total marks, percentage and displays the score card details. [Hint: Use list to store the marksin
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 thescore card
details.]
class Student:
def init (self,name,usn):
self.name = name
self.usn = usn
self.marklist = []
self.total_marks = 0
def getMarks(self):
print("Enter marks in 3 subjects:")
for i in range(3):
m = int(input())
self.marklist.append(m)
self.total_marks += m
def display(self):
print("Name:", self.name)
print("USN:", self.usn )
print("Marks:", self.marklist)
print("Total: " , self.total_marks)
print("Percentage: " , self.total_marks/3)
name = input("Enter your name: ")
usn = input("Enter your USN: ")
s1 = Student(name, usn)
s1.getMarks()
s1.display()
Output :
Enter your name: prath
Enter your USN: iew22ad001
Enter marks in 3 subjects:
DEPT. OF ISE, EWIT Page 16
PYTHON PROGRAMMING LABORATORY-BPCLK105B 2022-2023
85
86
96
Name: prath
USN: iew22ad001
Marks: [85, 86, 96]
Total: 267
Percentage: 89.0
DEPT. OF ISE, EWIT Page 17
EAST WEST INSTITUTE OF TECHNOLOGY
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
INSTITUTE VISION
To be an Institute of Academic Excellence in Technical and Management
Education on par with Global standards to meet the changing needs of the
Society.
INSTITUTE MISSION
To impart quality technical education that nurtures the young minds by
M1
providing the best of teaching learning process and state of the art infrastructure
M2 To foster technological advancement through research
M3 To inculcate holistic personality development through best practices
To implant ethical and social commitment that grooms the students to become
M4 responsible citizens
DEPARTMENT VISION
To provide Quality Technical Education in Information Science & Engineering
with Enriched Knowledge and Research Skills to Meet the Emerging
Challenges with Ethical values
DEPARTMENT MISSION
M1 To prepare students with strong fundamental concepts, analytical capability,
programming and problem solving skills
To impart Technical knowledge inculcating real time research experience to promote
M2 industrial & societal needs
To motivate and encourage skill based activities for transforming creative ideas to real
M3
time workable products
To prepare graduates to meet carrier challenges with a blend of social, human and ethical
M4
values
PROGRAM EDUCATIONAL OBJECTIVES (PEO’s)
PEO1 The graduates will have the ability to apply basic technical knowledge in the field of
Information Science & Engineering to design and develop solutions.
The graduates will succeed in proposing innovative ideas with substantial technical skills
PEO2 to achieve excellence in their career.
The graduates will be able to meet the challenges with a blend of social commitment and
PEO3 Ethical values.
PROGRAM SPECIFIC OUTCOMES (PSO’s)
PSO1 Graduates will be able to understand and apply technical knowledge and skills to solve
real time problems in the field of Information Science and Engineering.
Graduates can analyze, design and implement the innovative ideas to model real world
PSO2 problems using Programming and Algorithms to provide solutions with Ethical and
Management principles.