0% found this document useful (0 votes)
2 views22 pages

BPLCK105 Python Lab Manual For IOT

The document is a laboratory manual for the Introduction to Python Programming course for the 2nd semester B.E. students in the Department of CSE, focusing on IoT and Cyber Security. It includes various programming exercises such as calculating student marks, generating Fibonacci sequences, computing factorials, and analyzing text files. The manual aims to equip students with practical programming skills relevant to their field of study.

Uploaded by

helpboost1001
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)
2 views22 pages

BPLCK105 Python Lab Manual For IOT

The document is a laboratory manual for the Introduction to Python Programming course for the 2nd semester B.E. students in the Department of CSE, focusing on IoT and Cyber Security. It includes various programming exercises such as calculating student marks, generating Fibonacci sequences, computing factorials, and analyzing text files. The manual aims to equip students with practical programming skills relevant to their field of study.

Uploaded by

helpboost1001
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/ 22

DEPARTMENT OF CSE (IOT & CYBER SECURITY INCLUDING

BLOCK CHIAN TECHNOLOGY )

INTRODUCTION TO PYTHON PROGRAMMING LABORATORY


BPLCK105B/205B - 2ND SEMESTER B.E.
Academic Year – 2023-24

LAB MANUAL

Prepared by: Under the Guidance of:


Gayithri N DR. SAVITHA CHOUDARY
Assistant Professor Prof. and Head
Dept. of CSE Dept. of IOT

Department Vision and Mission

VISION

Building a Proficient Internet of Things Engineers with core values to solve real time problems.

MISSION
M1: To offer state-of-the-art Internet of Things education imparting skills for
building Cutting-edge and innovative applications with block chain and cyber
security.

M2: To inculcate ethically and socially committed Internet of Things professionals through
Value-added courses.

M3: Promoting research blend among students and enabling continuous learning
BPLCK105 – INTRODUCTION TO PYTHON PROGRAMMING
Manual

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.

Program:
studentname = input('Enter the Name of the student: ')
usn = input('Enter the USN of the student: ')
m1 = int(input('Enter the mark in first subject: '))
m2 = int(input('Enter the mark in second subject: '))
m3 = int(input('Enter the mark in third subject: '))
total = m1+m2+m3
percentage = round((total/300)*100)

print('\nName of the Student: ', studentname)


print('USN: ', usn)
print('Mark in Subject 1: ', m1)
print('Mark in Subject 2: ', m2)
print('Mark in Subject 3: ', m3)
print('Total Score = ', total)
print('Percentage = ', percentage)

if percentage >=90:
print('First Class Exemplary.')
elif percentage >=75 and percentage <90:
print('First Class with Distinction.')
elif percentage >=60 and percentage <75:
print('First Class.')
elif percentage >=35 and percentage <60:
print('Second Class.')
else:
print('Fail.')

Output:
Enter the Name of the student: Vinay R
Enter the USN of the student: 1HK22EC0127
Enter the mark in first subject: 90
Enter the mark in second subject: 95
Enter the mark in third subject: 99

Name of the Student: Vinay R


USN: 1HK22EC0127
Mark in Subject 1: 90
Mark in Subject 2: 95
Mark in Subject 3: 99
Total Score = 284
Percentage = 95
First Class Exemplary.
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.

Program:
personname = input('Enter the Name of the person: ')
yearofbirth = int(input('Enter the Year of Birth: '))
currentyear = 2023
age = currentyear - yearofbirth

print('\nName of the person: ', personname)


print('Year of Birth of the person: ', yearofbirth)
print('Age of the person: ', age)

if age >= 60:


print('The person is a Senior Citizen.')
else:
print('The person is not a Senior Citizen.')

Output:
Enter the Name of the person: Saba
Enter the Year of Birth: 1986

Name of the person: Saba


Year of Birth of the person: 1986
Age of the person: 37
The person is not a Senior Citizen.
2 a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.

Program:
f0 = 0
f1 = 1
N = int(input('Enter the Length of required Fibonacci Sequence: '))

if N<=0:
print('Enter Positive Integer value: ')
else:
i=0
print('Fibonacci Sequence for N = '+ str(N) + ' is: ')
while i<N:
print(f0)
fth = f0 + f1
f0 = f1
f1 = fth
i += 1
Output:
Enter the Length of required Fibonacci Sequence: 10
Fibonacci Sequence for N = 10 is:
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).

Factorial of a Number:
Program:
def factorial(N):
if N<0:
print('Enter the positive integer')
elif N==0:
print('The Factorial of 0 is 1')
elif N==1:
print('The Factorial of 1 is 1')
else:
i=1
f1=1
while i<=N:
fth=f1*i
f1=fth
i+=1
return fth

N=int(input('Enter the Number to find factorial: '))


fact = factorial(N)
print('The Factorial of ' +str(N)+ ' is ', fact)

Output:
Enter the Number to find factorial: 5
The Factorial of 5 is 120

Binomial coefficient:
Program:

def factorial(N):
if N<0:
print('Enter the positive integer')
elif N==0:
print('The Factorial of 0 is 1')
elif N==1:
print('The Factorial of 1 is 1')
else:
i=1
f1=1
while i<=N:
fth=f1*i
f1=fth
i+=1
return fth

N=int(input('Enter the value of N: '))


R=int(input('Enter the value of R '))
factN = factorial(N)
factR = factorial(R)
binomial = factN / (factR*factorial(N-R))
print('The Binomial coefficient for N= ' +str(N)+ ' and R= '+str(R)+ ' is ', binomial)
Output:
Enter the value of N: 7
Enter the value of R 3
The Binomial coefficient for N= 7 and R= 3 is 35.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.

Program:
N=int(input('Enter the number of elements: '))

lis=[]
for i in range(N):
lis.append(int(input('Enter the element: ')))

mean = round(sum(lis)/N,2)
print('\nMean is ',mean)

lis_mean=[]
for i in range(N):
lis_mean.append((lis[i] - mean)**2)

variance = round(sum(lis_mean)/N,2)
print('Variance is ', variance)

SD=round(variance**(1/2),2)
print('Standard deviation is ', SD)
if SD>=1.5:
print('High Dispersion, Low Reliability.')
else:
print('Low Dispersion, Reliable.')

Output:
Enter the number of elements: 8
Enter the element: 10
Enter the element: 12
Enter the element: 23
Enter the element: 23
Enter the element: 16
Enter the element: 23
Enter the element: 21
Enter the element: 16

Mean is 18.0
Variance is 24.0
Standard deviation is 4.9
High Dispersion, Low Reliability.
4. Read a multi-digit number (as chars) from the console. Develop a program to print
thefrequency of each digit with suitable message.

Program:

import pprint
message = input(‘Enter your input: ‘)
count = {}

for character in message:


count.setdefault(character, 0)
count[character] = count[character] + 1
print('Frequency of words appeared in the Sentence or paragraph\n')
pprint.pprint(count)
print()

for k,v in count.items():


print('Character \''+str(k)+'\' appeared ' + str(v)+ ' times')
Output:
Enter your input:
292749028574908279082574258979529847209846987620234456025657260974502874597264652
Frequency of words appeared in the Sentence or paragraph

{'0': 8,
'2': 15,
'3': 1,
'4': 10,
'5': 10,
'6': 7,
'7': 11,
'8': 8,
'9': 11}

Character '2' appeared 15 times


Character '9' appeared 11 times
Character '7' appeared 11 times
Character '4' appeared 10 times
Character '0' appeared 8 times
Character '8' appeared 8 times
Character '5' appeared 10 times
Character '6' appeared 7 times
Character '3' appeared 1 times
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]

Before starting the program save some content in .txt file, and use the path for the same file in
message1=open( )
Program:
import pprint
message1 =open(r"C:\Users\Sathish\Desktop\blutooth.txt")
message = message1.read()
message1.close()
print('The content in the file is: \n\n', message)
count = {}
for character in message.split():
count.setdefault(character, 0)
count[character] = count[character] + 1
print('\nFrequency of words appeared in the Sentence or paragraph\n')
pprint.pprint(count)
print()
sortedcount = sorted(count.items(), key=lambda x:x[1], reverse=True)
converttodict = dict(sortedcount)
print('\nSorted in descending order:\n\n',converttodict)
import itertools
sliceddict = dict(itertools.islice(converttodict.items(), 10))
print('\nTen Most frequently appeared word in a paragraph :\n\n',sliceddict)

Output:
The content in the file is:

Bluetooth technology is a high speed, low powered wireless technology that is used to transmit and
receive data serially. The Bluetooth transceivers consist of many devices such as mobile phones,
computers, and other electronic devices. Bluetooth technology is one of the best seminar topics for
electronics and communication students. In the embedded system many of electronic project
applications, controlling by Bluetooth technology. The Bluetooth technology gets second place in
Seminar topics for electronics and communication.
Frequency of words appeared in the Sentence or paragraph

{'Bluetooth': 5,
'In': 1,
'Seminar': 1,
'The': 2,
'a': 1,
'and': 4,
'applications,': 1,
'as': 1,
'best': 1,
'by': 1,
'communication': 1,
'communication.': 1,
'computers,': 1,
'consist': 1,
'controlling': 1,
'data': 1,
'devices': 1,
'devices.': 1,
'electronic': 2,
'electronics': 2,
'embedded': 1,
'for': 2,
'gets': 1,
'high': 1,
'in': 1,
'is': 3,
'low': 1,
'many': 2,
'mobile': 1,
'of': 3,
'one': 1,
'other': 1,
'phones,': 1,
'place': 1,
'powered': 1,
'project': 1,
'receive': 1,
'second': 1,
'seminar': 1,
'serially.': 1,
'speed,': 1,
'students.': 1,
'such': 1,
'system': 1,
'technology': 4,
'technology.': 1,
'that': 1,
'the': 2,
'to': 1,
'topics': 2,
'transceivers': 1,
'transmit': 1,
'used': 1,
'wireless': 1}

Sorted in descending order:

{'Bluetooth': 5, 'technology': 4, 'and': 4, 'is': 3, 'of': 3, 'The': 2, 'many': 2, 'electronic': 2, 'the': 2, 'topics':
2, 'for': 2, 'electronics': 2, 'a': 1, 'high': 1, 'speed,': 1, 'low': 1, 'powered': 1, 'wireless': 1, 'that': 1, 'used':
1, 'to': 1, 'transmit': 1, 'receive': 1, 'data': 1, 'serially.': 1, 'transceivers': 1, 'consist': 1, 'devices': 1, 'such':
1, 'as': 1, 'mobile': 1, 'phones,': 1, 'computers,': 1, 'other': 1, 'devices.': 1, 'one': 1, 'best': 1, 'seminar': 1,
'communication': 1, 'students.': 1, 'In': 1, 'embedded': 1, 'system': 1, 'project': 1, 'applications,': 1,
'controlling': 1, 'by': 1, 'technology.': 1, 'gets': 1, 'second': 1, 'place': 1, 'in': 1, 'Seminar': 1,
'communication.': 1}

Ten Most frequently appeared word in a paragraph :

{'Bluetooth': 5, 'technology': 4, 'and': 4, 'is': 3, 'of': 3, 'The': 2, 'many': 2, 'electronic': 2, 'the': 2, 'topics':
2}
6. Develop a program to sort the contents of a text file and write the sorted contents into a
separatetext file. [Hint: Use string methods strip(), len(), list methods sort(), append(), and
file methods open(), readlines(), and write()].

Program:
namelist=open(r'C:\Users\ Sathish\Desktop\namelist.txt')
namelist1=namelist.readlines()
namelist.close()
print('\n\n content available of the file is:\n\n',namelist1)
namelist1.sort()
sortedlist2=open(r'C:\Users\Sathish\Desktop\sortedlist.txt','w')
sortedlist2.writelines(namelist1)
sortedlist2.close()
print('\n\n Sorted content is :\n\n',namelist1)

Output:
content available of the file is:

['PRUTVIRAJ SANTOSHAKUMAR TUPPAD\n', 'PRUTHVI BT\n', 'PRIYANSHU KUMAR\n',


'PRIYA GT\n', 'PRAMOD SIDDAPPA PUJAR\n', 'PRADNESH R\n', 'PRADEEP.SS\n', 'POOJITHA
S\n', 'PAVANI M K\n', 'PARVEEN\n', 'PALLAVI N K\n', 'NUFAIZ ZULFIKAR\n', 'NITHIN
SADASHIV SHIPURE\n', 'NITHIN S\n', 'NISHANTH GOWDA VN\n', 'NISARGA K P\n',
'NISARGA CHIVATE\n', 'NISARGA C\n', 'NIRIKSHA C N\n', 'NIHAR FATHIMA\n', 'NAYAN
GOWDA R\n', 'NAWAZ AHMED\n', 'NAVYA SHREE R\n', 'NASIR KHAN\n', 'NARLA
VARSHITHA\n', 'NAGIREDDY NANDINI\n', 'MUTTURAJ\n', 'MUSARATH MUNTAHA\n',
'MUHAMMAD FARHAN\n', 'MOULYASHREE K M\n', 'MONISHA C\n', 'MONIKA B R\n',
'MOHAMMED UMAR ALI\n', 'MOHAMMED SINAN\n', 'MOHAMMED MAAZ H\n',
'MOHAMMED KHIZER PASHA\n', 'MOHAMMED KHIZER M D\n', 'MOHAMMED FARHAN\n',
'MOHAMMED BILAL PASHA\n', 'MOHAMMED ARSHAD\n', 'MOHAMMAD YAHYA\n',
'MELWIN JAIN\n', 'MEGHANA T V\n', 'MD AASIM AHMED\n', 'MARIA SWETHA A\n',
'MANDAPATI ANANYA\n', 'MAHASHWETHA G\n', 'M SATHYA SAI VENKATA
RANGAIAH\n', 'M JAGAN MOHAN REDDY\n', 'LIKITHA R\n', 'LIKHITH GOWDA S C\n',
'KUMAR K N\n', 'KULSUM HUZAIFA\n', 'KULADEEP GC\n', 'KOMAL\n', 'KOLLURI
AKANKSHA\n', 'KIRAN M N\n', 'KIRAN KUMAR N\n', 'KIRAN KUMAR GOUDAR \n', 'KIRAN
K S\n', 'KEERTHANA J\n', 'KEDARALINGA K S\n', 'KANCHANA H GOWDA']

Sorted content is :

['KANCHANA H GOWDA', 'KEDARALINGA K S\n', 'KEERTHANA J\n', 'KIRAN K S\n',


'KIRAN KUMAR GOUDAR \n', 'KIRAN KUMAR N\n', 'KIRAN M N\n', 'KOLLURI
AKANKSHA\n', 'KOMAL\n', 'KULADEEP GC\n', 'KULSUM HUZAIFA\n', 'KUMAR K N\n',
'LIKHITH GOWDA S C\n', 'LIKITHA R\n', 'M JAGAN MOHAN REDDY\n', 'M SATHYA SAI
VENKATA RANGAIAH\n', 'MAHASHWETHA G\n', 'MANDAPATI ANANYA\n', 'MARIA
SWETHA A\n', 'MD AASIM AHMED\n', 'MEGHANA T V\n', 'MELWIN JAIN\n', 'MOHAMMAD
YAHYA\n', 'MOHAMMED ARSHAD\n', 'MOHAMMED BILAL PASHA\n', 'MOHAMMED
FARHAN\n', 'MOHAMMED KHIZER M D\n', 'MOHAMMED KHIZER PASHA\n', 'MOHAMMED
MAAZ H\n', 'MOHAMMED SINAN\n', 'MOHAMMED UMAR ALI\n', 'MONIKA B R\n',
'MONISHA C\n', 'MOULYASHREE K M\n', 'MUHAMMAD FARHAN\n', 'MUSARATH
MUNTAHA\n', 'MUTTURAJ\n', 'NAGIREDDY NANDINI\n', 'NARLA VARSHITHA\n', 'NASIR
KHAN\n', 'NAVYA SHREE R\n', 'NAWAZ AHMED\n', 'NAYAN GOWDA R\n', 'NIHAR
FATHIMA\n', 'NIRIKSHA C N\n', 'NISARGA C\n', 'NISARGA CHIVATE\n', 'NISARGA K P\n',
'NISHANTH GOWDA VN\n', 'NITHIN S\n', 'NITHIN SADASHIV SHIPURE\n', 'NUFAIZ
ZULFIKAR\n', 'PALLAVI N K\n', 'PARVEEN\n', 'PAVANI M K\n', 'POOJITHA S\n',
'PRADEEP.SS\n', 'PRADNESH R\n', 'PRAMOD SIDDAPPA PUJAR\n', 'PRIYA GT\n',
'PRIYANSHU KUMAR\n', 'PRUTHVI BT\n', 'PRUTVIRAJ SANTOSHAKUMAR TUPPAD\n']
7. Develop a program to backing Up a given Folder (Folder in a current working directory)
intoa ZIP File by using relevant modules and suitable methods.

Program:

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 = 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:
newBase = os.path.basename(folder)
if filename.startswith(newBase) and filename.endswith('.zip'):
continue
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')

# Main Program
backupToZip(r'C:\Users\Sathish\Desktop\bb')

Output:
Done.
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.

Program:

def DivExp(a,b):
try:
c=a/b
except ZeroDivisionError:
print('Error: Division by zero')
else:
return c

a = int(input('Enter the Divident value of \'a\': '))


b = int(input('Enter the Divisor value of \'b\': '))
d=DivExp(a,b)

if d is not None:
print('The result of division is: ', d)
else:
print('The result of division is: infinity')

Output:
Enter the Divident value of 'a': 10
Enter the Divisor value of 'b': 0
Error: Division by zero
The result of division is: infinity
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 of N complex numbers.

Program:
class Complex:
def init (self, real, imag):
self.real = real
self.imag = imag

def add (self, other):


return Complex(self.real + other.real, self.imag + other.imag)

def str (self):


if self.imag >= 0:
return f"{self.real}+{self.imag}i"
else:
return f"{self.real}{self.imag}i"

def add_complex_numbers(num1, num2):


return num1 + num2

n = int(input("Enter the number of complex numbers: "))

complex_numbers = []
for i in range(n):
real, imag = input(f"Enter complex number {i+1}: ").split()
complex_numbers.append(Complex(float(real), float(imag)))

result = complex_numbers[0]
for i in range(1, n):
result = add_complex_numbers(result, complex_numbers[i])

print("Sum of the complex numbers is:", result)

Output:
Enter the number of complex numbers: 2
Enter complex number 1: 1 2
Enter complex number 2: 2 3
Sum of the complex numbers is: 3.0+5.0i
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 listto store the marks in three subjects and total marks. Use init () method to initialize
name, USNand 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.]

Program:
class Student:
def init (self, name, usn):
self.name = name
self.usn = usn
self.marks = []
self.total = 0

def getMarks(self):
for i in range(3):
marks = float(input(f"Enter marks for subject {i+1}: "))
self.marks.append(marks)
self.total += marks

def display(self):
print("Name:", self.name)
print("USN:", self.usn)
print("Marks:")
for i in range(3):
print(f"\tSubject {i+1}: {self.marks[i]}")
print("Total:", self.total)
print("Percentage:", round((self.total / 3),2))

# Main program
name = input("Enter name: ")
usn = input("Enter USN: ")

student = Student(name, usn)


student.getMarks()
student.display()

Output:
Enter name: Kanchana
Enter USN: 1HK22EC065
Enter marks for subject 1: 98
Enter marks for subject 2: 76
Enter marks for subject 3: 56
Name: Kanchana
USN: 1HK22EC065
Marks:
Subject 1: 98.0
Subject 2: 76.0
Subject 3: 56.0
Total: 230.0
Percentage: 76.67

You might also like