Lab Manual Python - Laboratory - 2022-23

Download as pdf or txt
Download as pdf or txt
You are on page 1of 20

Introduction to Python Programming Language BPCLK105B/205B

MAHARAJA INSTITUTE OF TECHNOLOGY THANDAVAPURA


NH 766, Nanjangud Taluk, Mysuru- 571 302
(An ISO 9001:2015 and ISO 21001:2018 Certified Institution)
(Affiliated to VTU, Belagavi and approved by AICTE, New Delhi)

DEPARTMENT OF ELECTRONICS & COMMUNICATION


ENGINEERING

INTRODUCTION TO PYTHON PROGRAMMING


(BPLCK105B/205B)
LAB MANUAL

2022-23

Prepared By
Mrs.Bhagyalakshmi.V
Assistant Professors
Department of ECE
MIT Thandavapura

Dept of ECE,MIT 1
Introduction to Python Programming Language BPCLK105B/205B

Instructions to the Laboratory

 Students must present a College ID card before entering the python programming lab.
 Every user must make an entry in the login book while entering in the python programming lab
and also at the time of exit from the lab.
 Students must write the programs in the observation book to be executed and complete the
record writing of previous week observations before entering the Lab.
 Users are strictly prohibited from modifying or deleting any important files and install any
software or settings in the computer.
 If any problem arises, please bring the same to the notice of lab in-charge.
 Students are not allowed to use personal Pen Drives etc., in Lab.
 In case of theft / destruction of the computers or peripherals, double the cost of the lost will be
charged from the student/user.
 DO NOT leave your personal belongings at the computer. The College is not responsible for
items left behind.
 Users must turn-off the computer before leaving the computer lab.
 Silence must be maintained in the lab at all times.
 The lab must be kept clean and tidy at all times.
 Conversation, discussion, loud talking & sleeping are strictly prohibited.
 No bags/ hand bags/ rain coats/ casual wears will be allowed inside the python programming
lab, however observation book and lab record may be allowed.

Dept of ECE,MIT 2
Introduction to Python Programming Language BPCLK105B/205B

INTRODUCTION TO PYTHON PROGRAMMING LANGUAGE

Python is a popular programming language. It was created by Guido van Rossum, and released in
1991. Python is a high-level, general-purpose programming language. Its design philosophy
emphasizes code readability with the use of significant indentation.
Python is dynamically-typed and garbage-collected. It supports multiple programming paradigms,
including structured (particularly procedural), object-oriented and functional programming. It is often
described as a "batteries included" language due to its comprehensive standard library.

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software development.
 Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
 Python has a simple syntax similar to the English language.
 Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
 Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
 Python can be treated in a procedural way, an object-oriented way or a functional way.

Python Syntax compared to other programming languages

 Python was designed for readability, and has some similarities to the English language with
influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming languages
which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of loops,
functions and classes. Other programming languages often use curly-brackets for this purpose.

Indentation
Python uses whitespace indentation, rather than curly brackets or keywords, to delimit blocks. An
increase in indentation comes after certain statements; a decrease in indentation signifies the end of the
current block. Thus, the program's visual structure accurately represents its semantic structure. This
feature is sometimes termed the off-side rule. Some other languages use indentation this way; but in
most, indentation has no semantic meaning. The recommended indent size is four spaces.

Dept of ECE,MIT 3
Introduction to Python Programming Language BPCLK105B/205B

Statements and control flow


Python's statements include:

 The assignment statement, using a single equals sign =


 The if statement, which conditionally executes a block of code, along with else and elif (a
contraction of else-if)
 The for statement, which iterates over an iterable object, capturing each element to a local variable
for use by the attached block
 The while statement, which executes a block of code as long as its condition is true.
 The try statement, which allows exceptions raised in its attached code block to be caught and
handled by except clauses; it also ensures that clean-up code in a finally block is always run
regardless of how the block exits
 The raise statement, used to raise a specified exception or re-raise a caught exception
 The class statement, which executes a block of code and attaches its local namespace to a class, for
use in object-oriented programming.
 The def statement, which defines a function or method.
 The with statement, which encloses a code block within a context manager (for example, acquiring
a lock before it is run, then releasing the lock; or opening and closing a file), allowing resource-
acquisition-is-initialization (RAII)-like behaviour and replacing a common try/finally idiom.
 The break statement, which exits a loop.
 The continue statement, which skips the rest of the current iteration and continues with the next
 The del statement, which removes a variable—deleting the reference from the name to the value,
and producing an error if the variable is referred to before it is redefined.
 The pass statement, serving as a NOP, syntactically needed to create an empty code block.
 The assert statement, used in debugging to check for conditions that should apply
 The yield statement, which returns a value from a generator function; used to implement co
routines
 The return statement, used to return a value from a function.
 The import statement, used to import modules whose functions or variables can be used in the
current program.

Dept of ECE,MIT 4
Introduction to Python Programming Language BPCLK105B/205B

Python divides the operators in the following groups:

 Arithmetic operators

 Assignment operators

Dept of ECE,MIT 5
Introduction to Python Programming Language BPCLK105B/205B

 Comparison operators

 Logical operators

 Identity operators

 Membership operators

Dept of ECE,MIT 6
Introduction to Python Programming Language BPCLK105B/205B

 Bitwise operators

Python Data Types

There are different types of data types in Python. Some built-in Python data types are:

 Numeric data types: int, float, complex


 String data types: str
 Sequence types: list, tuple, range
 Binary types: bytes, byte array, memory view
 Mapping data type: dict
 Boolean type: bool
 Set data types: set, frozenset

Dept of ECE,MIT 7
Introduction to Python Programming Language BPCLK105B/205B

 Applications

*****************

Dept of ECE,MIT 8
Introduction to Python Programming Language BPCLK105B/205B

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.

print("enter the student name")


name =input()
print("enter your USN")
USN=input()
print("enter your physics marks")
p=int(input())
print("enter your chemistry marks")
c=int(input())
print("enter your maths marks")
m=int(input())
Total=p+c+m
percentage=(Total/300)*100
print("The student details are")
print("student name is",name)
print("student USN is",USN)
print("physics marks is",p)
print("chemistry marks is",c)
print("maths marks is",m)
print("the total marks obtained is",Total)
print("the percentile obtained is ",percentage)
print("ALL THE BEST")

Out put:
enter the student name
AAA
enter your USN
4MN22ECXXX
enter your physics marks
90
enter your chemistry marks
95
enter your maths marks
89
The student details are
student name is AAA
student USN is 4MN22ECXXX
physics marks is 90
chemistry marks is 95
maths marks is 89
the total marks obtained is 274
the percentage obtained is 91.33
ALL THE BEST

*****************

Dept of ECE,MIT 9
Introduction to Python Programming Language BPCLK105B/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.

print("Enter your name")


name=input()
print("Enter your year of birth")
year_of_birth=int(input())
year_of_birth=int(input())
print("Enter present year ")
present_year=int(input())
age= present_year - year_of_birth
print(“Your Age is”,age)
if age>60:
print("You are a senior citizen")
else:
print("You are not a senior citizen")

Output:
Enter your name
hamza
Enter your year of birth
1979
Enter present year
2023
You are not a senior citizen

*****************

Dept of ECE,MIT
10
Introduction to Python Programming Language BPCLK105B/205B

2. a. Develop a program to generate Fibonacci sequence of length (N). Read N from the console.

print (“Enter the length of Fibonacci Series”)


n=int (input())
n1=0
n2=1
print (“Fibonacci Series for the length”+ n +”is as follows”)
print (n1)
print (n2)
for x in range(2,n):
n3=n1+n2
print (n3)
n1=n2
n2=n3

Output:

Enter the length of Fibonacci Series


5
Fibonacci Series for the length 5 is as follows
0
1
1
2
3

*****************

Dept of ECE,MIT
11
Introduction to Python Programming Language BPCLK105B/205B

b. Write a function to calculate factorial of a number. Develop a program to compute binomial


coefficient (Given N and R).

def fact(num)
fact=1
for i in range (num,0,-1):
fact=fact*i
return fact
N=int (input(“Enter the value for N”))
R=int (input(“Enter the value for R”))
NF=fact(N)
RF=fact(R)
print(“Factorial of “+N+”is”, NF)
NRF=fact(N-R)
BMC=NF/(RF*(NRF))
print (“Binomial co efficient is”, BMC)

Output:

Enter the value for N


4
Enter the value for R
2
Factorial of 4 is 24
Binomial co efficient is 6

*****************

Dept of ECE,MIT
12
Introduction to Python Programming Language BPCLK105B/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.

import math
def mean(data):
n=len(data)
mean=sum(data)/n
return mean
def variance(data):
n=len(data)
mean=sum(data)/n
deviation=((x-mean)**2 for x in data)
variance =sum(deviation)/n
return variance
def stddev(data):
var=variance(data)
stddev=math.sqrt(var)
return stddev
n=[]
while True:
print("to stop press -1\t"+"enter the number"+"str(len(n))"+"is")
num=int(input())
if num==-1:
break
n=n+[num]
print(n)
print("mean",mean(n))
print("variance",variance(n))
print("stddev",stddev(n))

Out put:
to stop press -1 enter the number str(len(n))is
30
to stop press -1 enter the number str(len(n))is
2
to stop press -1 enter the number str(len(n))is
5
to stop press -1 enter the number str(len(n))is
-1
[30, 2, 5]
mean 12.333333333333334
variance 157.55555555555551
stddev 12.552113589175152

*****************

Dept of ECE,MIT
13
Introduction to Python Programming Language BPCLK105B/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.

number=input("enter the number\n")


count={}
L1=[]
for character in number:
if character not in L1:
L1.append(character)
count.setdefault(character,0)
count[character]+=1
print("the frequency of digit is as fallows")
print(L1)
for x in L1:
print (x,'=',count.get(x),'times')
Output:
enter the number
4567776544123
the frequency of digit is as fallows
[4,5,6,7,7,7,6,5,4,4,1,2,3]
4 = 3 times
5 = 2 times
6 = 2 times
7 = 3 times
1 = 1 times
2 = 1 times
3 = 1 times

*****************

Dept of ECE,MIT
14
Introduction to Python Programming Language BPCLK105B/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]

myfile=open("C:\\Users\\STUDENT\\Desktop\\python.txt",'r')
c=myfile.read()
myfile.close()
type(c)
c1=c.split()
freq={}
for c1 in c1:
if c1 in freq:
freq[c1]=freq[c1]+1
else:
freq[c1]=1
f1={}
print("frequency of words of 10 most repeating words")
for n,f in freq.items():
f1[n]=f
fsorted=sorted(f1.items(),key=lambda x:x[1])
fsorted.reverse()
fn=fsorted[0:10]
import pprint
print(pprint.pprint(fn))

Output:
frequency of words of 10 most repeating words
[('is', 5),
('name', 3),
('branch', 2),
('your', 2),
('my', 2),
('you.', 1),
('meet', 1),
('to', 1),
('nice', 1),
('sam:Ok', 1)]

*****************

Dept of ECE,MIT
15
Introduction to Python Programming Language BPCLK105B/205B

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

file=open("C:\\Users\\STUDENT\\Desktop\\py.v.txt")
s=file.read()
file.close()
split_file=s.split()
sorted_f=sorted(split_file)
file2=open("C:\\Users\\STUDENT\\Desktop\\sortnew.txt",'w')
for x in sorted_f:
file2.write(f'{x}\n')
print('done')
file2.close()

Output:
Done

*****************

Dept of ECE,MIT
16
Introduction to Python Programming Language BPCLK105B/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 zipfile
file=zipfile.ZipFile('new.zip','w')
file.write("C:\\Users\\Student\\Desktop\\python.txt",compress_type=zipfile.ZIP_DEFLATED)
print("done")
file.close()
file=zipfile.ZipFile('new.zip')
print(file.namelist())
file.extractall('D:\\')
file.close()

Output:
done
['Users/Student/Desktop/python.txt/']

*****************

Dept of ECE,MIT
17
Introduction to Python Programming Language BPCLK105B/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>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,p):
assert a>0, “the a is less than 0”
if b==0:
raise Exception('b should not be equal to 0')
c=a/b
return c
try:
print("enter the a value")
a=int(input())
print ('enter the b values')
b=int(input())
print(DivExp(a,b))
except Exception as err:
print(err)

Output:
enter the a value
1
enter the b values
0

b should not be equal to 0

*****************

Dept of ECE,MIT
18
Introduction to Python Programming Language BPCLK105B/205B

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.

class Complex:
def __init__(self,tempReal,tempImaginary):
self.real=tempReal;
self.imaginary=tempImaginary;
def addComp(self,c1,c2):
temp=Complex(0,0)
temp.real=c1.real+c2.real;
temp.imaginary=c1.imaginary+c2.imaginary;
return temp;
if __name__=='__main__':
print("enter the complex number 1 real and imaginary part")
a=int(input())
b=int(input())
c1=Complex(a,b);
print("Complex number 1:",c1.real,"+i"+str(c1.imaginary))
print("\nenter the complex number 2real and imaginary")
c=int(input())
d=int(input())
c2=Complex(c,d);
print("Complex number 2:",c2.real,"+i"+str(c2.imaginary))
c3=Complex(0,0)
c3=c3.addComp(c1,c2);
print("\nSum of complex number:",c3.real,"+i"+str(c3.imaginary))

Output:
enter the complex number 1 real and imaginary part
33
44
Complex number 1: 33 +i44
enter the complex number 2real and imaginary
22
45
Complex number 2: 22 +i45
Sum of complex number: 55 +i89

*****************

Dept of ECE,MIT
19
Introduction to Python Programming Language BPCLK105B/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:
name=''
USN=''
lst=[]
def __init__(self,lst,name,USN):
self.name=name
self.marks=lst
self.USN=USN
def getMarks(self):
for x in range(3):
m=int(input('enter the marks:'))
self.lst.append(m)
def display(self):
print(\n'student name:',self.name)
print('student USN:',self.USN)
for x in range(0,3):
print(f'marks in sub{x+1}:{self.lst[x]}')
def totalmarks(self):
self.totalM=sum(self.lst)
self.perc=(self.totalM/300)*100
print('total marks=',self.totalM)
print('percentage obtained=',self.perc)
n=input('enter the name of the student\n')
usn=input('enter the student usn\n')
p=student([],n,usn)
p.getMarks()
p.display()
p.totalmarks()
Output:
enter the name of the student
AAA
enter the student usn
4MN22ECXXX
enter the marks:99
enter the marks:99
enter the marks:99
student name: AAA
student USN: 4MN22ECXXX
marks in sub1:99
marks in sub2:99
marks in sub3:99
total marks= 297
percentage obtained= 99.0
*****************

Dept of ECE,MIT
20

You might also like