Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
Children’s Education Society ®
THE OXFORD COLLEGE OF ENGINEERING
Hosur Road, Bommanahalli, Bengaluru-560 068
Website:www.theoxford.edu/http://theoxfordengg.org/ Email : [email protected]
(Approved by AICTE, New Delhi & Affiliated to VTU, Belgaum)
DEPARTMENT OF ARTIFICIAL INTELLIGENCE & MACHINE LEARNING
LABORATORY MANUAL [2022 SCHEME]
SUBJECT NAME & CODE : Introduction to Python Programming Lab
(BPLCK205B)
SCHEME – B.E (ISE) : 2022 SCHEME
SEMESTER : II-semester C2)
FACULTY INCHARGE:
Ms S.Visalini, Asst. Professor, Dept.of ISE
The Oxford College of Engineering , Dept.of ISE
Page 1
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
Syllabus: Introduction to Python Programming
The Oxford College of Engineering , Dept.of ISE
Page 2
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
CourseCode BPLCK105B/ CIEMarks 5
205B 0
TeachingHours/Week(L:T:P:S) 2:0:2:0 SEEMarks 5
0
Course Type Integrate TotalMarks 10
d 0
Credits 03 ExamHours 0
3
CourseObjectives:
●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.
Sl. PracticePrograms
No.
1 Calculation of Area of Circle, Rectangle, Square and Triangle
2 Calculation of Simple Interest
3 Check whether the given number is even or odd
4 Convert string case
5 Check for the palindrome, prime number,perfect square….etc
ListofproblemsforwhichstudentsshoulddeveloptheprogramandexecuteintheLaboratory
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 a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.
b. Write a function to calculate factorial of a number. Develop a program to compute binomial
coefficient (Given N and R).
3 Read N numbers from the console and create a list. Develop a program to print mean, variance and
standard deviation with suitable messages.
4 Read a multi-digit number (as chars) from the console. Develop a program to print the frequency of
each digit with suitable message.
5 Develop a program to print 10 most frequently appearing words in a text file. [Hint: Use
dictionarywith distinct words and their frequency of occurrences. Sort the dictionary in the reverse
order of
frequency and display dictionary slice of first 10 items]
6 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()].
7 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.
8 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.
9 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
The Oxford College of Engineering , Dept.of ISE
Page 3
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
of N complex numbers.
1 Develop a program that uses class Student which prompts the user to enter marks in three subjects
0 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.]
Continuous Internal Evaluation (CIE):
The CIE marks for the theory component of the IC shall be 30 marks and for the laboratory
component 20 Marks.
CIE for the practical component of the IC
On completion of every experiment/program in the laboratory, the students shall be evaluated
and marks shall be awarded on the same day. The 15 marks are for conducting the experiment
and preparation of the laboratory record, the other 05 marks shall be for the test conducted at the
end of the semester.
The CIE marks awarded in the case of the Practical component shall be based on the continuous
evaluation of the laboratory report. Each experiment report can be evaluated for 10 marks. Marks of
all experiments’ write-ups are added and scaled down to 15 marks.
The laboratory test (duration 03 hours) at the end of the 15th week of the semester /after
completion of all the experiments (whichever is early) shall be conducted for 50 marks and scaled
down to 05 marks.
Scaled-down marks of write-up evaluations and tests added will be CIE marks for the laboratory
component of IC/IPCC for 20 marks.
The minimum marks to be secured in CIE to appear for SEE shall be 12 (40% of maximum marks)
in the theory component and 08 (40% of maximum marks) in the practical component. The laboratory
component of the IC/IPCC shall be for CIE only. However, in SEE, the questions from the laboratory
component shall be included. The maximum of 05 questions is to be set from the practical component
of IC/IPCC, the total marks of all questions should not be more than 25 marks.
The theory component of the IC shall be for both CIE and SEE.
Semester End Examination (SEE):
The theory portion of the Integrated Course shall be for both CIE and SEE, whereas the practical portion
will have a CIE component only. Questions mentioned in the SEE paper shall include questions from the
practicalcomponent).
SuggestedLearningResources:
1. Al Sweigart,“Automate the Boring Stuff with Python”,1st Edition, No Starch Press, 2015.
2. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”, 2nd Edition, Green Tea
Press, 2015. (Available under CC-BY-NC license at http://greenteapress.com/thinkpython2/thinkpython2.pdf
WeblinksandVideoLectures(e-Resources):
●https://www.learnbyexample.org/python/
● https://www.learnpython.org/
● https://pythontutor.com/visualize.html#mode=edit
The Oxford College of Engineering , Dept.of ISE
Page 4
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
Table of Contents
Sl.No Program Page No
1. a. Develop a program to read the student details like Name, USN, and Marks in three 6
subjects. Displaythe 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 asenior citizen or not.
2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from 8
the console.
b. Write a function to calculate factorial of a number. Develop a program to compute
binomial coefficient (Given N and R).
3. Read N numbers from the console and create a list. Develop a program to print mean, 9
variance and standard deviation with suitable messages.
4. Read a multi-digit number (as chars) from the console. Develop a program to print the 11
frequency of each digit with suitable message.
5. Develop a program to print 10 most frequently appearing words in a text file. [Hint: Use 11
dictionarywith distinct words and their frequency of occurrences. Sort the dictionary in
the reverse order of frequency and display dictionary slice of first 10 items]
6. Develop a program to sort the contents of a text file and write the sorted contents into a 12
separate textfile. [Hint: Use string methods strip(), len(), list methods sort(), append(), and
file methods open(),readlines(), and write()].
7. Develop a program to backing Up a given Folder (Folder in a current working directory) 13
into a ZIPFile by using relevant modules and suitable methods.
8. Write a function named DivExp which takes TWO parameters a, b and returns a value c 14
(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.
9. Define a function which takes TWO objects representing complex numbers and returns 15
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.
10. Develop a program that uses class Student which prompts the user to enter marks in three 17
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.]
The Oxford College of Engineering , Dept.of ISE
Page 5
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
Setting up the Python Environment
Downloading and Installing Python
You can download Python for Windows, OS X, and Ubuntu for free from http://python.org/downloads/. On
Windows, download the Python installer and double-click it. Follow the instructions the installer displays on
the screen to install Python, as listed here:
1. Select Install for All Users and then click Next.
2. Install to the C:\Python34 folder by clicking Next.
3. Click Next again to skip the Customize Python section.
If you’re running Ubuntu, you can install Python from the Terminal by following these steps:
1. Open the Terminal window.
2. Enter sudo apt-get install python3.
3. Enter sudo apt-get install idle3.
4. Enter sudo apt-get install python3-pip.
Starting IDLE\
While the Python interpreter is the software that runs your Python programs, the interactive development
environment (IDLE) software is where you’ll enter your programs, much like a word processor. Let’s start
IDLE now.
• On Windows 7 or newer, click the Start icon in the lower-left corner of your screen, enter IDLE in the
search box, and select IDLE (Python GUI).
• On Ubuntu, select Applications->Accessories->Terminal and then enter idle3. (You may also be able to
click Applications at the top of the screen, select Programming, and then click IDLE 3.)
Program1. 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.
print('Enter student name')
sname = input()
print('Enter USN number')
usn = input()
print('Enter subject1 marks')
marks1 = int(input())
print('Enter subject2 marks')
marks2 = int(input())
print('Enter subject3 marks')
The Oxford College of Engineering , Dept.of ISE
Page 6
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
marks3 = int(input())
total = marks1 + marks2 + marks3
percentage = total / 3
print('Name of a student = ' + sname)
print('USN = ' + usn)
print('Total marks = ' + str(total))
print('Percentage = ' + str(percentage))
Output:
Enter student name
sanaa
Enter USN number
1234
Enter subject1 marks
70
Enter subject2 marks
80
Enter subject3 marks
90
Name of a student=sanaa
USN=1234
Total marks=240
Percentage=80.0
Program 1.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.
print('What is your name')
name = input()
print('What is your year of birth')
yob = int(input()) # yob = year of birth
age = 2023 - yob
if age >= 60:
print('You are ' + str(age) + ' years old so You are a senior citizen')
else:
print('You are ' + str(age) + ' years old so you are not a senior citizen')
Output:
The Oxford College of Engineering , Dept.of ISE
Page 7
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
case1
What is your name
sanaa
What is your year of birth
2000
You are 23 years old so you are not a senior citizen
case2
What is your name
Raana
What is your year of birth
1950
You are 73 years old so You are a senior citizen
Program 2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.
N = int(input("How many terms? "))
n1, n2 = 0, 1
count = 0
if N <= 0:
print("Please enter a positive integer")
elif N == 1:
print(n1)
else:
print("Fibonacci sequence:")
while count < N:
print(n1)
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
Output:
Case1
How many terms? 5
Fibonacci sequence:
0
1
1
2
3
The Oxford College of Engineering , Dept.of ISE
Page 8
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
Case2
How many terms? -4
Please enter a positive integer
Program 2.b. Write a function to calculate factorial of a number. Develop a program to compute
binomial coefficient (Given N and R).
def factorial(z):
def factorial(z):
if z == 1:
return 1
else:
return z * factorial(z - 1)
def binomial_coefficient(n, r): # n > r
ncr = factorial(n) / (factorial(r) * factorial(n - r))
return ncr
n = int(input("Enter the value of N: "))
r = int(input("Enter the value of R: "))
print("The factorial of " + str(n) + " is:", factorial(n))
print("The binomial coefficient is:", binomial_coefficient(n, r))
Output:
Enter the value of N: 5
Enter the value of R: 3
The factorial of 5 is: 120
The binomial coefficient is: 10.0
Program 3. Read N numbers from the console and create a list. Develop a program to print mean,
variance and standard deviation with suitable messages.
def mean(data):
n = len(data)
return sum(data) / n
def variance(data):
n = len(data)
mean_val = mean(data)
deviations = [(x - mean_val) ** 2 for x in data]
return sum(deviations) / n
def stdev(data):
import math
var = variance(data)
return math.sqrt(var)
The Oxford College of Engineering , Dept.of ISE
Page 9
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
data = []
N = int(input("Enter number of elements: "))
print('Enter %d Elements' % N)
for i in range(N):
data.append(int(input()))
print('Created list is:', data)
print("Mean of the sample is", mean(data))
print("Variance of the sample is", variance(data))
print("Standard Deviation of the sample is", stdev(data))
Output:
Enter number of elements : 5
Enter 5 Elements
4
2
5
9
7
Created list is: [4, 2, 5, 9, 7]
Mean of the sample is 5.4
Variance of the sample is 7.3
Standard Deviation of the sample is 2.701851217221259
Program 4. 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 multidigit number: ')
d = {}
for i in num:
d.setdefault(i, 0)
d[i] += 1
print(d)
for i in d:
print('Frequency of ' + str(i) + ' is ' + str(d[i]))
Output:
The Oxford College of Engineering , Dept.of ISE
Page 10
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
Enter a multidigit number: 2237728484
{'2': 3, '3': 1, '7': 2, '8': 2, '4': 2}
Frequency of 2 is 3
Frequency of 3 is 1
Frequency of 7 is 2
Frequency of 8 is 2
Frequency of 4 is 2
Program 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 itertools
text = open('c:\\hello1.txt')
d = {}
for line in text.readlines():
line = line.strip().lower()
words = line.split()
for i in words:
d.setdefault(i, 0)
d[i] += 1
print('Frequency of each word in a text file:\n', d)
sort = dict(sorted(d.items(), key=lambda x: x[1], reverse=True))
print('\nSorted dictionary in reverse order:\n', sort)
out = dict(itertools.islice(sort.items(), 10))
print('\n10 Most frequently appearing words in a text file:\n', out)
text.close()
Output:
Frequency of each word in a text file:
{'say': 1, 'you': 3, 'want': 2, 'to': 2, 'rename': 1, 'every': 3, 'file': 3, 'in': 2, 'some': 1, 'folder': 1, 'and': 1, 'also': 1,
'subfolder': 1, 'of': 1, 'that': 2, 'folder.': 1, 'is,': 1, 'walk': 1, 'through': 1, 'the': 1, 'directory': 1, 'tree,': 1,
'touching': 1, 'each': 1, 'as': 1, 'go.': 1}
Sorted dictionary in reverse order:
{'you': 3, 'every': 3, 'file': 3, 'want': 2, 'to': 2, 'in': 2, 'that': 2, 'say': 1, 'rename': 1, 'some': 1, 'folder': 1, 'and': 1,
'also': 1, 'subfolder': 1, 'of': 1, 'folder.': 1, 'is,': 1, 'walk': 1, 'through': 1, 'the': 1, 'directory': 1, 'tree,': 1,
'touching': 1, 'each': 1, 'as': 1, 'go.': 1}
10 Most frequently appearing words in a text file:
{'you': 3, 'every': 3, 'file': 3, 'want': 2, 'to': 2, 'in': 2, 'that': 2, 'say': 1, 'rename': 1, 'some': 1}
Program 6. 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(),
The Oxford College of Engineering , Dept.of ISE
Page 11
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
readlines(), and write()].
list1 = []
FileName = open('c:\\spam.txt')
data = FileName.readlines()
print('Content of text file before sorting:\n', data)
for line in data:
list1.append(line.strip())
list1.sort()
print('\nContent of text file after sorting:\n', list1)
FileName.close()
FileName = open("c:\\eggs.txt", 'w')
for i in range(len(list1)):
FileName.write(list1[i] + '\n')
FileName.close()
Output:
Content of text file before sorting:
['sanaa\n', 'ashwini\n', 'chitra\n', 'zophie\n']
Content of text file after sorting:
['ashwini', 'chitra', 'sanaa', 'zophie']
Program 7. 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 zipfile, os
def backupToZip(folder):
folder = os.path.abspath(folder)
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number += 1
print('Creating %s...' % zipFilename)
backupZip = zipfile.ZipFile(zipFilename, 'w')
for foldername, subfolders, filenames in os.walk(folder):
print('Adding files in %s...' % foldername)
backupZip.write(foldername)
The Oxford College of Engineering , Dept.of ISE
Page 12
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
for filename in filenames:
if filename.startswith(os.path.basename(folder) + '_') and filename.endswith('.zip'):
continue
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
backupToZip('c:\\delicious')
Output:
Creating delicious_4.zip...
Adding files in c:\delicious...
Adding files in c:\delicious\walnut...
Adding files in c:\delicious\walnut\waffles...
Done.
Program 8. 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.
def DivExp(a, b):
assert a > 0, 'a value should be greater than zero'
if b == 0:
raise Exception('Value of b cannot be zero')
return a / b
a = int(input('Enter the value of a: '))
b = int(input('Enter the value of b: '))
try:
print('Value of c =', DivExp(a, b))
except Exception as err:
print(err)
Output:
case1(when a<0)
Enter the value of a: -2
Enter the value of b: 4
a value should be greater than zero
The Oxford College of Engineering , Dept.of ISE
Page 13
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
case2(when a>0 and b=0)
Enter the value of a: 4
Enter the value of b: 0
Value of b cannot be zero
case3(when a>0 and b!=0)
Enter the value of a: 10
Enter the value of b: 8
Value of c = 1.25
Program 9. Define a function which takes TWO objects representing complex numbers and returns
new complex number with an 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.
class Complex:
def __init__(self, real=0, img=0):
self.real = real
self.img = img
def __add__(self, other):
out = Complex()
out.real = self.real + other.real
out.img = self.img + other.img
return out
def __str__(self):
return '%.2d+%.2d j' % (self.real, self.img)
N = int(input('Enter the number of complex numbers: '))
a = []
for i in range(0, N):
real = int(input('Enter the real part of complex number ' + str(i) + ': '))
img = int(input('Enter the imaginary part of complex number ' + str(i) + ': '))
The Oxford College of Engineering , Dept.of ISE
Page 14
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
a.append(Complex(real, img))
if N % 2 != 0:
a.append(Complex(0, 0))
res = Complex()
for i in range(0, N, 2):
temp = a[i] + a[i+1]
res += temp
print(res)
Output:
Enter the number of complex numbers:4
Enter the real part of complex number 0: 2
Enter the imaginary part of complex number 0: 3
Enter the real part of complex number 1: 1
Enter the imaginary part of complex number 1: 4
Enter the real part of complex number 2: 5
Enter the imaginary part of complex number 2: 2
Enter the real part of complex number 3: 3
Enter the imaginary part of complex number 3: 6
11+15 j
OR
class Complex:
'''
creats objects of complex type
'''
def sum(a,b):
c=Complex()
c.real=a.real+b.real
c.img=a.img+b.img
return c
a=Complex()
a.real=int(input('Enter the real part of a: '))
a.img=int(input('Enter the img part of a: '))
The Oxford College of Engineering , Dept.of ISE
Page 15
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
b=Complex()
b.real=int(input('Enter the real part of b: '))
b.img=int(input('Enter the img part of b: '))
c=sum(a,b)
print(c.real,'+',c.img,'j')
Output:
Enter the real part of a:2
Enter the img part of a:3
Enter the real part of b:4
Enter the img part of b:5
6+9j
Program 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. [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):
self.name = input('Enter the student name: ')
self.usn = input('Enter the student USN: ')
self.marks = []
def getMarks(self):
total = 0
for i in range(3):
self.marks.append(int(input('Enter the marks of subject ' + str(i+1) + ': ')))
total += self.marks[i]
self.marks.append(total)
def Display(self):
print('------------**********-------------\n')
print('Student\'s score card:')
The Oxford College of Engineering , Dept.of ISE
Page 16
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
print('Student name:', self.name)
print('Student USN:', self.usn)
for i in range(3):
print('Subject ' + str(i+1) + ' marks:', self.marks[i])
print('Total marks:', self.marks[3])
print('Percentage:', self.marks[3]/3)
s = Student()
s.getMarks()
s.Display()
Output:
Enter the student name: xxx
Enter the student USN: 123
Enter the marks of subject 1: 70
Enter the marks of subject 2: 65
Enter the marks of subject 3: 75
------------**********-------------
Student's score card:
Student name: xxx
Student USN: 123
subject 1 marks: 70
subject 2 marks: 65
subject 3 marks: 75
Total marks: 210
Percentage: 70.0
The Oxford College of Engineering , Dept.of ISE
Page 17
Introduction to Python Programming Lab(BPLCK205B)
__________________________________________________________________________
The Oxford College of Engineering , Dept.of ISE
Page 18