IPP Lab Manual
IPP Lab Manual
IPP Lab Manual
Dept.ofCSE,CBIT,Kolar
2
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
CourseOutcome(CourseSkillSet)
Attheendofthecoursethestudentwillbeableto:
1. Demonstrate proficiency in handling loops and creation of functions.
2. Identify the methods to create and manipulate lists, tuples and dictionaries.
3. Develop programs for string processing and file organization
4. Interpret the concepts of Object-Oriented Programming as used in Python.
AssessmentDetails(bothCIEandSEE)
The weightage of Continuous Internal Evaluation (CIE) is 50% and for Semester End Exam (SEE) is 50%.
The minimum passing mark for the CIE is 40% of the maximum marks (20 marks out of 50). The minimum
passing mark for the SEE is 35% of the maximum marks (18 marks out of 50). A student shall be deemed to
have satisfied the academic requirements and earned the credits allotted to each subject/ course if the student
secures not less than 35% (18 Marks out of 50) in the semester-end examination(SEE), and a minimum of
40% (40 marks out of 100) in the sum total of the CIE (Continuous Internal Evaluation) and SEE (Semester
End Examination) taken together.
ContinuousInternalEvaluation(CIE):
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
SuggestedLearningResources:
Textbooks
1. Al Sweigart,“Automate the Boring Stuff with Python”,1stEdition, No Starch Press, 2015.
2. Allen B. Downey, “Think Python: How to Think Like a Computer Scientist”, 2 ndEdition, Green
Tea Press, 2015.
WeblinksandVideoLectures(e-Resources):
1. https://www.learnbyexample.org/python/
2. https://www.learnpython.org/
3. https://pythontutor.com/visualize.html#mode=edit.
4. https://tinyurl.com/4xmrexre
5. https://github.com/sushantkhara/Data-Structures-And-Algorithmswith Python / raw/main/
Python%203%20_%20400%20exercises%20and%20solutions%20for%20beginn ers.pdf
Dept.ofCSE,CBIT,Kolar
3
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
What is Python?
Python is a popular programming language. It was created by Guido van Rossum, and released in
1991.
It is used for:
Web development (server-side)
Software development
Mathematics
System scripting
Why Python?
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.
Steps to run in different platforms
Run the interactive shell by launching IDLE, which is installed with Python
On Windows, open the Start menu, select All Programs ▸ Python 3.3, and then select IDLE (Python
GUI).
On OS X, select Applications ▸ MacPython 3.3 ▸ IDLE.
On Ubuntu, open a new Terminal window and enter idle3.
Flowchart:
• A flow chart is a pictorial representation of an algorithm. That is flowchartconsists
ofsequence ofinstructions thatarecarriedoutin analgorithm.Allthestepsare drawnformof
differentshapesof
boxes,circleandconnectingarrows.Flowchartsaremainlyusedtohelpprogrammertounderstandthel
ogicoftheprogram.
Startorendoftheflowchart(program)
Inputoroutputoperation
Decisionmakingandbranching
Connector
Predefinedcomputationorprocess(usedwithfu
nctionsareused)
Repetitionoraloopwhichisnormallyusedtoexecuteagro
upofinstructions foraspecifiesnumberoftimes
Flow ofcontrol
Dept.ofCSE,CBIT,Kolar
4
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
PracticePrograms
p=10
t=20
r=30
si=(p*t*r)/100
Output
Simple interest is 0.6
x=10
y=20
temp=x
x=y
y=temp
Output
Before swapping 10 20
After swapping 20 10
Dept.ofCSE,CBIT,Kolar
5
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
Output
Enter length of first side: 10
Enter length of second side:20
Enter length of three side:30
Semi perimeter of triangle is 30
Dept.ofCSE,CBIT,Kolar
6
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
PARTA
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.
total=sub1+sub2+sub3
Per=(total/300)*100
Output
Dept.ofCSE,CBIT,Kolar
7
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
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.
Output
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
2. (a) Develop a program to generate Fibonacci sequence of length (N). Read N from
the console.
N = int(input("Enter N value: "))
n1, n2 = 0, 1
count = 0
if N <= 0:
print("Please enter a positive integer")
elif N == 1:
print("Fibonacci sequence upto",N,":")
print(n1)
else:
print("Fibonacci sequence:")
while count < N:
print(n1)
nxt = n1 + n2
n1 = n2
n2 = nxt
count += 1 # count++
Output
Dept.ofCSE,CBIT,Kolar
9
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
if R == 1 or R == N:
print(1)
elif R > N:
print(0)
else:
b_coef=factorial(N)/( factorial(N-R) * factorial(R) )
print(b_coef)
Output
Dept.ofCSE,CBIT,Kolar
10
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
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
n=int(input("Enter N value:"))
Mylist=[]
print("Enter a value")
fori in range(n):
v=int(input())
Mylist.append(v)
lenv=len(Mylist)
if(lenv == 0):
print("List should not be empty")
else:
sumv=sum(Mylist)
meanval = sumv/lenv
temp=0
fori in range(lenv):
temp += ((Mylist[i] - meanval) * (Mylist[i] - meanval))
vari = temp / lenv;
sd = math.sqrt(vari)
print("Mean value: ",meanval)
print("Varience: ",vari)
print("Standard Deviation: ",sd)
Output
Dept.ofCSE,CBIT,Kolar
11
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
4. Read a multi-digit number (as chars) from the console. Develop a program to print
the frequency of each digit with suitable message.
Output
Dept.ofCSE,CBIT,Kolar
12
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
except:
print("File can't open")
Output
Dept.ofCSE,CBIT,Kolar
13
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
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()].
fh_in = open(infile,"r")
data=fh_in.readlines()
lst = []
fori in range(len(data)):
lst.append(data[i].strip())
lst.sort()
fh_in.close()
fori in lst:
fh_out.write(i)
fh_out.write("\n")
fh_out.close()
Output
Dept.ofCSE,CBIT,Kolar
14
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
importzipfile
zf = zipfile.ZipFile("myzipfile.zip", "w")
zf.write(dirname)
zf.write(os.path.join(dirname, filename))
zf.close()
Output
Dept.ofCSE,CBIT,Kolar
15
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
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.
import sys
defDivExp(a,b):
try:
c=a/b
return c
exceptAssertionError as msg:
sys.exit(msg)
res=DivExp(v1,v2)
Output
Dept.ofCSE,CBIT,Kolar
16
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
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,r,i):
self.real = r
self.imag = i
defaddcom(self, other):
return Complex(self.real + other.real, self.imag + other.imag)
N=int(input("Enter a number of complex numbers: "))
sum=Complex(0,0)
fori in range(N):
print("\nComplex Number:",i+1)
a=int(input("Enter real part: "))
b=int(input("Enter imaginary part: "))
c=Complex(a,b)
sum=sum.addcom(c)
print("\nAfter Sum:",sum.real,"+",sum.imag,"i")
Output
Dept.ofCSE,CBIT,Kolar
17
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
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.Marks=self.getMarks()
defgetMarks(self):
mrk=[]
fori in range(3):
print("Subject",i+1)
m=int(input())
mrk.append(m)
mrk.append(sum(mrk))
returnmrk
def display(self):
print("\nName: ",self.Name)
print("USN: ",self.USN)
print("----------------------------")
print("============================")
per=(self.Marks[3]/300)*100 print("----------------------------")
s=Student()
s.display()
Output
Dept.ofCSE,CBIT,Kolar
19
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
VivaQuestions:
1. Define Python.
2. List the applications of python
3. Python an interpreted language. Explain.
4. List the rule to declare a variable in python
5. How python handles the exceptions?
6. Mention three types of errors encountered in python programs
7. Differentiate between compiler and interpreter.
8. Explain break and continue statement
9. Explain if and elif statements
10. What are String slices
11. What are lists? Lists are mutable. Justify the statement
15. What are python modules? Name some commonly used built-in modules in Python?
Dept.ofCSE,CBIT,Kolar
20
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23
DO’SANDDON’TS
Do’s
1. Do wear ID card and follow dress code.
2. Do log off the computers when you finish.
3. Do ask the staff for assistance if you need help.
4. Do keep your voice low when speaking to others in the LAB.
5. Do ask for assistance in downloading any software.
6. Do make suggestions as to how we can improve the LAB.
7. In case of any hardware related problem, ask LAB in charge for solution.
8. If you are the last one leaving the LAB, make sure that the staff in charge of the LAB
is informed to close the LAB.
9. Be on time to LAB sessions.
10. Do keep the LAB as clean as possible.
Don’ts
1. Do not use mobile phone inside the lab.
2. Don’t do anything that can make the LAB dirty (like eating, throwing waste papers etc).
3. Do not carry any external devices without permission.
4. Don’t move the chairs of the LAB.
5. Don’t interchange any part of one computer with another.
6. Don’t leave the computers of the LAB turned on while leaving the LAB.
7. Do not install or download any software or modify or delete any system files on any
lab computers.
8. Do not damage, remove, or disconnect any labels, parts, cables, or equipment.
9. Don’t attempt to bypass the computer security system.
10. Do not read or modify other user’s file.
11. If you leave the lab, do not leave your personal belongings unattended. We are
not responsible for any theft.
Dept.ofCSE,CBIT,Kolar
21