Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Final Python Lab Manual

The document is a laboratory manual for the Introduction to Python Programming course at Jain Institute of Technology, Davanagere. It outlines the vision and mission of the institute and the computer science department, followed by a series of programming exercises designed to enhance students' Python skills. Each exercise includes problem statements and sample code to guide students in developing their programming capabilities.

Uploaded by

komalagv103
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Final Python Lab Manual

The document is a laboratory manual for the Introduction to Python Programming course at Jain Institute of Technology, Davanagere. It outlines the vision and mission of the institute and the computer science department, followed by a series of programming exercises designed to enhance students' Python skills. Each exercise includes problem statements and sample code to guide students in developing their programming capabilities.

Uploaded by

komalagv103
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 20

Arka Educational and Cultural Trust (R)

JAIN INSTITUTE OF
TECHNOLOGY, DAVANAGERE
(A Unit of Jain group of Institutions, Bangalore)
Affiliated to VTU, Belagavi |Approved by AICTE, New Delhi

Department of CS&E and


IS&E

Introduction to
Python Programming
(BPLCK105B/205B)
Laboratory Manual

I/II Semester
2022-23
Arka Educational & Cultural Trust (Regd.)
JAIN INSTITUTE OF TECHNOLOGY, DAVANAGERE
(A Unit of Jain Group of Institutions, Bangalore)

VISION AND MISSION


OF INSTITUTE

Vision of the Institute:

Technical manpower development to build professionally excellent, globally competitive, socially


responsible engineers and entrepreneurs with human values.

Mission of the Institute:

To provide quality education through innovation in teaching to create technologically


M1
competent engineers.
To Achieve excellence in research and development to advance science and
M2
technology to the ever changing needs of society.
To create outstanding professionals by facilitating state of the art platform capable of
M3
working in multi-cultural environment.
M4 To produce quality engineers with high ethical standards and professionalism.
Arka Educational & Cultural Trust (Regd.)
JAIN INSTITUTE OF TECHNOLOGY, DAVANAGERE
(A Unit of Jain Group of Institutions, Bangalore)

VISION AND MISSION OF


THE PROGRAM

Vision of the Department:

To develop socially responsible computer engineers and entrepreneurs with strong academic excellence,
technical backgrounds, research and innovation, intellectual skills and creativity to cater the needs of IT
Industry and society by adopting professional ethics.

Mission of the Department:

To impart center of excellence by offering technical education and imbibing


M1
experiential learning skills to achieve teaching learning process.
Providing a Platform to discover and engage research and innovation strengths,
M2 talents, passions through collaborations, government, private agencies and
industries.
Creating an environment to inculcate moral principles, professionalism and
M3
responsibilities towards the society.
Course Title: Introduction to Python Programming
Laboratory
Course Code: BPLCK105B/205B
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 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]

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

9. 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.

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.]
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

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.

stdntname= input("Enter the Name of the Student ")


stdntusn= input("Enter the USN ")
stdntmarks1= int(input("Enter the Marks of Subject1: "))
stdntmarks2= int(input("Enter the Marks of Subject2: "))
stdntmarks3= int(input("Enter the Marks of Subject3: "))

totalmarks= stdntmarks1+stdntmarks2+stdntmarks3
percentage = (totalmarks/300)*100

spcstr = "=" * 70
print(spcstr)
print("The name of the student is :", stdntname)
print("The Student USN is :", stdntusn)
print("The Marks secured in Subject1 :", stdntmarks1)
print("The Marks secured in Subject2 :", stdntmarks2)
print("The Marks secured in Subject3 :", stdntmarks3)
print(spcstr)

output:

Enter the Name of the Student Meghana


Enter the USN 4jd22cs026
Enter the Marks of Subject1: 85
Enter the Marks of Subject2: 75
Enter the Marks of Subject3: 95
====================================================================
The name of the student is : Meghana
The Student USN is : 4jd22cs026
The Marks secured in Subject1 : 85
The Marks secured in Subject2 : 75 The
Marks secured in Subject3 : 95
===================================================================
The total Marks Scored is: 255 The
percentage is: 85.0

Jain Institute of Technology, 1


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

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.

from datetime import date


name = input("Enter Name")
birthyear = int(input("Enter the birth year"))

curryear = date.today().year
age = curryear - birthyear

print(age)
if age>=60:
print("person is senior citizen")
else:
print("Person is not senior citizen")

output:

Enter Name abc


Enter the birth year1952
The age is
71
person is senior citizen

Jain Institute of Technology, 2


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

2. a. Develop a program to generate Fibonacci sequence of length (N).


Read N from the console.

n= int(input("Enter the value of n "))


fib0 = 0
fib1 = 1
print("The Fibonacci Series of n numbers are ")
for x in range (0,n):
if x == 0:
print(fib0)
elif x == 1:
print(fib1)
else:
fib2=fib0+fib1
print(fib2)
fib0=fib1
fib1=fib2

output:
Enter the value of n 5
The Fibonacci Series of n numbers are
0
1
1
2
3

b. Write a function to calculate factorial of a number. Develop a


program to compute binomial coefficient (Given N and R)

def factorial(n):
if n==0:
return 1
elif n==1:
return 1
else:
return n*factorial(n-1)

n= int(input("Enter the value of n"))


r= int(input("enter the value of r"))
ncr= factorial(n)/(factorial(n-r)*factorial(r))
print("The result of nCr is")
print(ncr)

output:
Enter the value of n5
enter the value of r2
The result of nCr is
10.0

Jain Institute of Technology, 3


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

3. 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= []
n= int(input("Enter the Number of Elements: "))
for i in range(n):
val= int(input("Enter the element :"))
mylist.append(val)
sum=0
for elem in mylist:
sum=sum+elem
mean = sum/n
print("Sum=",sum)
print("Mean=",mean)

variance = 0
for elem in mylist:
variance+= (elem-mean)*(elem-mean)
variance=variance/n
print("variance=",variance)

stddev= sqrt(variance)
print("Stddev=",stddev)

output:
Enter the Number of Elements: 3
Enter the element :15
Enter the element :10
Enter the element :10
Sum= 35
Mean= 11.666666666666666
variance= 5.5555555555555545
Stddev= 2.357022603955158

Jain Institute of Technology, 4


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

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 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 : 11232
The number entered is : 11232
3 occurs 1 times
2 occurs 2 times
1 occurs 2 times

Jain Institute of Technology, 5


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

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 sys
import string
import os.path

fname = input("Enter the filename : ") #sample file text.txt also


provided

if not os.path.isfile(fname):
print("File", fname, "doesn’t exists")
sys.exit(0)

infile = open(fname, "r")

filecontents = ""

for line in infile:


for ch in line:
if ch not in string.punctuation:
filecontents = filecontents + ch
else:
filecontents = filecontents + " " #replace punctuations
and \n with space

wordFreq = {}
wordList = filecontents.split()

#Calculate word Frequency

for word in wordList:


if word not in wordFreq.keys():
wordFreq[word] = 1
else:
wordFreq[word] += 1

#Sort Dictionary based on values in descending order


sortedWordFreq = sorted(wordFreq.items(), key=lambda x:x[1],
reverse=True )

#Display 10 most frequently appearing words with their count


print("\n===================================================")
print("10 most frequently appearing words with their count")
print("===================================================")
for i in range(10):
print(sortedWordFreq[i][0], "occurs", sortedWordFreq[i][1],
"times")

Jain Institute of Technology, 6


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

output:
Enter the filename : 1.txt
===================================================
10 most frequently appearing words with their count
===================================================
i occurs 3 times
am occurs 3 times
and occurs 2 times
abc occurs 1 times
working occurs 1 times
in occurs 1 times
CS occurs 1 times
E occurs 1 times
an occurs 1 times
assistant occurs 1 times

Jain Institute of Technology, 7


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

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()].

import os.path
import sys

fname = input("Enter the filename whose contents are to be sorted: ")

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()
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")
for line in rdFile:
print(line, end="")

Jain Institute of Technology, 8


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

output:

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

File containing sorted content sorted.txt created successfully


sorted.txt contains 11 lines
Contents of sorted.txt
=================================================================
april
feb
friday
jan
march
monday
saturday
sunday
thursday
tuesday
Wednesday

Jain Institute of Technology, 9


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

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 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 : jit
Archive myZip.zip created successfully

Jain Institute of Technology, 10


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

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 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 : 10
AssertionError: a should be greater than 0

Enter a value for a : 1


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

Enter a value for a : -3


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

Jain Institute of Technology, 11


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

9. 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 imaginary 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)

print("Sum of two Complex Numbers")


c3.showComplex()

#Addition of N (N >=2) complex numbers


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

for i in range(num):
print("Object", i+1)

Jain Institute of Technology, 12


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

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 : 3


Object 1
Enter the real part : 2
Enter the imaginary part : 3
Object 2
Enter the real part : 3
Enter the imaginary part : 2
Object 3
Enter the real part : 5
Enter the imaginary part : 6

Entered Complex numbers are :


(2)+i(3)
(3)+i(2)
(5)+i(6)
Sum of N complex numbers is (10)+i(11)

Jain Institute of Technology, 13


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

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, 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("%15s"%("NAME"), "%12s"%("USN"),"%8s"%"MARKS1",
"%8s"%"MARKS2","%8s"%"MARKS3","%8s"%"TOTAL", "%12s"%
("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)
def main():
s1 = Student()
s1.getMarks()
s1.display()
main()

Jain Institute of Technology, 14


Davanagere
Introduction to Python Programming Laboratory
(BPLCK105B/205B)

output:
Enter student Name : Pooja
Enter student USN : 4jd21cs045
Enter marks in Subject 1 : 85
Enter marks in Subject 2 : 92
Enter marks in Subject 3 : 75
=====================================================================
SCORE CARD DETAILS
=====================================================================
NAME USN MARKS1 MARKS2 MARKS3 TOTAL PERCENTAGE
=====================================================================
Pooja 4jd21cs045 85 92 75 252 84.00
=====================================================================

Jain Institute of Technology, 15


Davanagere

You might also like