[go: up one dir, main page]

0% found this document useful (0 votes)
15 views20 pages

IPP Lab Manual

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

INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23

Introduction to Python Programming


CourseCode BPLCK205B CIEMarks 50
TeachingHours/Week (L:T:P:S) 0:0:2:0 SEEMarks 50
TotalHoursofPedagogy -- TotalMarks 100
Credits 01 ExamHours 03
CourseObjectives:
1. Learn the syntax and semantics of the Python programming language.
2. Illustrate the process of structuring the data using lists, tuples
3. Appraise the need for working with various documents like Excel, PDF, Word and Others.
4. Demonstrate the use of built-in functions to navigate the file system.
5. Implement the Object Oriented Programming concepts in Python.
Sl.No. PracticePrograms
1 To add two numbers
2 CalculationofSimpleInterest
3 Swapping of two numbers
4 Checkwhetherthegivennumberisevenorodd
5 To find semi perimeter of triangle
6 To find largest of three numbers
PART A-List of problems for which students should develop the program and execute
intheLaboratory
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) Computetheroots ofaquadraticequationbyacceptingthecoefficients.Print
appropriatemessages.
(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>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 addition of N complex numbers.
10 Implement structures to read, write and compute average- marks of the students, list the
students scoring above and below the average marks for a class of N students.

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.

Symbolsused Meaningassociatedwith symbols

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

1. To add two numbers


a=10
b=20
sum=a+b
print(‘sum of two numbers is’, sum)
Output:
sum of two numbers 30

2. Calculation of Simple Interest

p=10

t=20

r=30

si=(p*t*r)/100

print(‘Simple interest is’,si)

Output
Simple interest is 0.6

3. Swapping of two numbers

x=10

y=20

print(‘Before swapping’, x,y)

temp=x

x=y

y=temp

print(‘After swapping’, x,y)

Output
Before swapping 10 20

After swapping 20 10

Dept.ofCSE,CBIT,Kolar
5
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23

4. Check whether the given number is even or odd


num=int(input(‘Enter the number:’)
if(num%2)==0:
print(‘Number is even’)
else:
print(‘Number is odd’)
Output
Enter thenumber:6
Number is even

5. To find semi perimeter of triangle


a = int(input(‘Enter length of first side:’))
b = int(input(‘Enter length of second side:’))
c = int(input(‘Enter length of third side:’))
SP=(a+b+c)/2
print(‘Semi perimeter of triangle is’,SP)

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

6. To find largest of three numbers


a = int(input(‘Enter first number:’))
b = int(input(‘Enter second number:’))
c = int(input(‘Enter third number:’))
largest = 0
if a>b and a>c:
largest=a
if b > a and b > c:
largest=b
if c > a and c > b:
largest = c
print(largest,’is the largest of three numbers’)
Output
Enter first number: 10

Enter second number:20

Enter third number:30

30 is the largest of three numbers

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.

print("Enter Student details: ")


Name=input("Enter a Name: ")
USN=input("Enter USN: ")

sub1=int(input("Enter marks of the first subject: "))


sub2=int(input("Enter marks of the second subject: "))
sub3=int(input("Enter marks of the third subject: "))

total=sub1+sub2+sub3
Per=(total/300)*100

print("Student details: ")


print("Name: ",Name)
print("USN: ",USN)
print("Total Marks: ",total)
print("Percentage: ",Per)

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.

Name=input("Enter name of a person: ")


year_of_birth=int(input("Enter year(yyyy) of birth: "))
age=2023-year_of_birth
if age>=60:
print("The person is Senior citizen")
else:
print("The person is not Senior citizen")

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

2. (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
else:
return n * factorial(n-1)

N = int(input("Enter a value for N: "))


R = int(input("Enter a value for R: "))

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.

str1 = input("Enter a multi-digit number: ")


d = dict()
for c in str1:
if c in d.keys():
d[c] = d[c] + 1
else:
d[c] = 1
fork,v in d.items():
print("Number ",k," has frequency: ",v)

Output

Dept.ofCSE,CBIT,Kolar
12
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23

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]
fname = input('Enter the file name: ')
try:
fhand = open(fname,"r")
counts = dict()
for line in fhand:
words = line.split()
for word in words:
if word in counts:
counts[word] += 1
else:
counts[word] = 1
counts=sorted(counts,reverse=True)
print(counts[:11])

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

infile = input("Enter input file name: ")

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

outfile=input("Enter output file name: ")

fh_out = open(outfile, "w")

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

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

importzipfile

fold=input("Enter Directory name: ")

#zipf = fold +".zip"

#zf = zipfile.ZipFile(zipf, "w")

zf = zipfile.ZipFile("myzipfile.zip", "w")

fordirname, subdirs, files in os.walk(fold):

zf.write(dirname)

for filename in files:

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:

assert a>0, "Expected number should be positive"

assert b!=0, "Can't divide by zero"

c=a/b

return c

exceptAssertionError as msg:

sys.exit(msg)

v1=int(input("Enter first number: "))

v2=int(input("Enter second number: "))

res=DivExp(v1,v2)

print(v1,"%",v2," is: ",res)

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.USN=input("Enter Student USN: ")

self.Name=input("Enter student name: ")

self.Marks=self.getMarks()

defgetMarks(self):

mrk=[]

print("Enter the marks of subjects out of 100")

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("Subject 1 Marks: ",self.Marks[0])

print("Subject 2 Marks: ",self.Marks[1])

print("Subject 3 Marks: ",self.Marks[2])


Dept.ofCSE,CBIT,Kolar
18
INTRODUCTION TO PYTHON PROGRAMMING (BPLCK205B) 2022-23

print("============================")

print(" Total: ",self.Marks[3])

per=(self.Marks[3]/300)*100 print("----------------------------")

print(" percentage: ",per)

print("Enter student Details: ")

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

12. What is the difference between list and tuples in Python?

13. What are the key features of Python?


14. What are Dict and List comprehensions?

15. What are python modules? Name some commonly used built-in modules in Python?

16. What are local variables and global variables in Python?

17. Is python case sensitive?

18. Is indentation required in python?

19. What are functions in Python?

20. What is __init__?

21. How can you generate random numbers in Python?

22. What is the difference between range &xrange?

23. How do you write comments in python?

24. What is a dictionary in Python?

25. What does len() do?

26. How can files be deleted in Python?

27. What are Python libraries? Name a few of them.

28. What is split used for?


29. How to import modules in python?

30. How to create an empty class 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

You might also like