PES Institute of Technology and Management
NH-206, Sagar Road, Shivamogga-577204
Department of Computer Science and Engineering
Affiliated to
VISVESVARAYA TECHNOLOGICAL UNIVERSITY
Jnana Sangama, Belagavi, Karnataka –590018
Laboratory Manual
I/II Semester B.E
Introduction to Python Programming Lab
(BPLCK105B/205B)
Prepared By ,
Mrs. Suchitha H S,
Assistant Professor,
Department of CSE
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
CONTENTS
Introduction to Python Programming
CourseCode BPLCK105B/205B CIEMarks 50
TeachingHours/Week(L:T:P:S) 2:0:2:0 SEEMarks 50
Course Type Integrated TotalMarks 100
Credits 03 ExamHours 03
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.
Sl.No. PracticePrograms
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
List of problemsforwhichstudentsshoulddeveloptheprogramandexecuteintheLaboratory
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
2 aa. 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
3 coefficient (Givenfrom
Read N numbers N and R).console and create a list. Develop a program to print mean, variance and
the
standard deviation with suitable messages.
4 Read a multi-digit number (as chars) from the console. Develop a program to print the frequency
of
5
each digitawith
Develop suitable
program tomessage.
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
6 frequency
Develop a and display
program to dictionary slice of of
sort the contents first 10 items]
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(),
7 readlines(),
Develop and write()].
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.
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
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
10 addition a program that uses class Student which prompts the user to enter marks in three
Develop
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.]
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
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
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
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.)
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
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.
sname=input('Enter student name: ')
usn=input('Enter USN number: ')
marks1=int(input('Enter subject1 marks: '))
marks2=int(input('Enter subject2 marks: '))
marks3=int(input('Enter subject3 marks: '))
total=marks1+marks2+marks3
percentage=(total/300)*100
print(‘*******Students Details********’)
print('Name of a student='+sname)
print('USN='+usn)
print('Total marks='+str(total))
print('Percentage='+str(percentage))
Output:
Enter student name: abc
Enter USN number: 4PM24cs001
Enter subject1 marks: 80
Enter subject2 marks: 60
Enter subject3 marks: 90
*******Students Details********
Name of a student=abc
USN=4PM24cs001
Total marks=230
Percentage=76.66666666666667
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.
name=input('Enter your name: ')
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
yob=int(input('Enter your year of birth: ')) #yob=year of birth
Current_year=int(input('Enter the current year: '))
age=Current_year-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:
case1
Enter your name: abc
Enter your year of birth: 2005
Enter the current year: 2025
You are 20 years old so you are not a senior citizen
case2
Enter your name: xyz
Enter your year of birth: 1950
Enter the current year: 2025
You are 75 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.
def fib(nterms):
n1, n2 = 0, 1
count = 0
if nterms <= 0:
print("Please enter a positive integer")
else:
print("Fibonacci sequence for number "+str(nterms)+" is")
while count < nterms:
print(n1)
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
nth = n1 + n2
n1 = n2
n2 = nth
count += 1
number = int(input("How many terms? "))
fib(number)
Output:
Case1
How many terms? 5
Fibonacci sequence for number 5 is
0
1
1
2
3
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):
if z==1:
return 1
else:
return z* factorial(z-1)
def binomial_coefficient(n,r): #n must be>r
ncr=(factorial(n)) / (factorial(r) * factorial(n-r))
return ncr
n=int(input("Enter the value of N: "))
print("The factorial of "+str(n) +" is:",factorial(n))
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
r=int(input("Enter the value of R: "))
print("The binomial coefficient is:",binomial_coefficient(n,r))
Output:
Enter the value of N: 5
The factorial of 5 is: 120
Enter the value of R: 3
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)
mean = sum(data) / n
return mean
def variance(data):
n = len(data)
mean = sum(data) / n
deviations = [(x - mean) ** 2 for x in data]
variance = sum(deviations) / n
return variance
def stdev(data):
import math
var = variance(data)
std_dev = math.sqrt(var)
return std_dev
data = []
N = int(input("Enter number of elements : "))
print('Enter %d Elements' %N)
for i in range(N):
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
data.append(int(input()))
print('Created list is: ',data)
print("Mean of the sample is "+ str(mean(data)))
print("Variance of the sample is " + str(variance(data)))
print("Standard Deviation of the sample is "+ str(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]=d[i]+1
print(d)
for i in d:
print('Frequency of '+str(i)+' is '+str(d[i]))
Output:
Enter a multidigit number: 2237728484
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
{'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 is a string
line = line.strip()
line = line.lower()
words = line.split(" ") #words is a list
for i in words:
d.setdefault(i,0)
d[i]=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:
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
{'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(), readlines(), and
write()].
list1=[]
FileName = open('c:\\spam.txt') #opening a file in read mode
data=FileName.readlines() #data is a list
for line in data:
list1.append(line.strip()) #list1 is also a list
print('Content of text file before sorting: \n', data)
list1.sort() # sorting the contents of file spam.txt
print('\nContent of text file after sorting: \n',list1)
FileName.close()
FileName = open("c:\\eggs.txt",'w') #opening file in write mode
for i in range(len(list1)):
FileName.write(list1[i] +'\n') #writing sorted content into file eggs.txt
FileName.close()
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
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) # make sure folder is absolute
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = 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)
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')
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
Output:
Creating delicious_1.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')
else:
c=a/b
return c
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
case2(when a>0 and b=0)
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
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)+': '))
a.append(Complex(real,img))
if N%2!=0:
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
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: '))
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
a.img=int(input('Enter the img part of a: '))
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):
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
print('------------**********-------------',end='\n\n')
print('Student\'s score card: ')
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
Dept of CSE, PESITM Shivamogga
PES Institute of Technology and Manage-
ment
Department of Computer Science and Engineering
Dept of CSE, PESITM Shivamogga