0% found this document useful (0 votes)
16 views10 pages

Python Programming Lab Manual 2022-23

This document is a lab manual for an Introduction to Python Programming course at Jawaharlal Nehru New College of Engineering. It outlines various programming tasks and objectives aimed at developing proficiency in Python, including handling data structures, file operations, and object-oriented programming concepts. The manual includes specific programming exercises, course outcomes, and objectives for students to achieve by the end of the course.

Uploaded by

arfaza838
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views10 pages

Python Programming Lab Manual 2022-23

This document is a lab manual for an Introduction to Python Programming course at Jawaharlal Nehru New College of Engineering. It outlines various programming tasks and objectives aimed at developing proficiency in Python, including handling data structures, file operations, and object-oriented programming concepts. The manual includes specific programming exercises, course outcomes, and objectives for students to achieve by the end of the course.

Uploaded by

arfaza838
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Jawaharlal Nehru New College of Engineering

NAVULE (SAVALANGA Road), Shivamogga – 577204. Karnataka

Department of Artificial Intelligence and Machine Learning

Introduction to Python
Programming lab

(BPLCK/205B)
II Sem

LAB MANUAL
(2022-23)

Prepared by

Mr. Sayyed Johar


Assistant
Professor Dept. of
AIML, JNNCE
Shivamogga
Introduction to Python
Programming lab
Sub Code : BPLCK/205B Hours/Week: 02
IA Marks: 25 Total Hours: 20
Sl. No.
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>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. 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.]

Dept. of AIML, JNNCE, Shivamogga


Course Outcome

At the end of the course students will be able to

CO1. Demonstrate proficiency in handling loops and creation of functions.

CO2. Identify the methods to create and manipulate lists, tuples and dictionaries.

CO3. Develop programs for string processing and file organization.

CO4. Interpret the concepts of Object-Oriented Programming as used in Python.

Course objectives

 Learn the syntax and semantics of the Python programming language.

 Illustrate the process of structuring the data using lists, tuples

 Appraise the need for working with various documents like Excel, PDF, Word and Others.

 Demonstrate the use of built-in functions to navigate the file system

 .Implement the Object-Oriented Programming concepts in Python.

Dept. of AIML, JNNCE, Shivamogga


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.

name=input('Enter the student name')


usn=input('Enter the student USN')
marks1=int(input('Enter Marks1'))
marks2=int(input('Enter Marks2'))
marks3=int(input('Enter Marks3'))
tot_marks=marks1+marks2+marks3
per=tot_marks/3
print("Student Details :\nName:%s\nUSN:%s\nTotal_Marks=%3d\nPercentage=%3f" % (name,
usn,tot_marks,per))

OUTPUT:
Enter the student name KUMAR
Enter the student USN 4JNAI22000
Enter Marks1 89
Enter Marks290
Enter Marks399
Student Details :
Name: KUMAR
USN: 4JNAI22000
Total_Marks=278
Percentage=92.666667

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.
import datetime
name=input('Enter the person name')
year=int(input('Enter year of birth'))
today = [Link]()
cyear = [Link]
age = cyear-year
if age >=60:

print('%s is Senior Citizen'%name)

else:
print('%s is not a Senior Citizen'%name)
OUTPUT:
Enter the person name KUMAR AI
Enter year of birth 1961
KUMAR AI is Senior Citizen

Enter the person nameABC


Enter year of birth1983
ABC is not a Senior Citizen

Dept. of AIML, JNNCE, Shivamogga


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


fib1=1
fib2=1
print(fib1)
print(fib2)
for i in range(0,N):
fib3=fib1+fib2
print(fib3)
fib1=fib2
fib2=fib3

OUTPUT:
Enter the value of N8
1
1
2
3
5
8
13
21
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<=1:
return 1
else:
return n*factorial(n-1)

n=int(input('Enter n'))

#ans=factorial(n)

k=int(input('Enter k'))
binomial_coeff=factorial(n)/(factorial(k)*(factorial(n-k)))
print(n,k,binomial_coeff)

print('facorial of %d is %d'%(n,factorial(n)))

OUTPUT:
Enter n4
Enter k2
4 2 6.0
facorial of 4 is 24

Dept. of AIML, JNNCE, Shivamogga


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


n=int(input('Enter n'))
l=list()
for i in range(n):
num=int(input())
[Link](num)
mean=sum(l)/len(l)
sm=0
for i in range(n):
diff=(l[i]-mean)**2
sm=sm+diff
variance=sm/len(l)
stdev=sqrt(variance)
print(mean,variance,stdev)

OUTPUT:
Enter n 4
Enter 4 numbers
12
2
4
5
5.75 18.91666668 4.349329450

[Link] 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')
digits=list()
for i in range(10):
[Link](0)
for i in num:
digits[int(i)]=digits[int(i)]+1
print(digits)

OUTPUT:
Enter a number343434343
[0, 0, 0, 5, 4, 0, 0, 0, 0, 0]

Dept. of AIML, JNNCE, Shivamogga


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 operator
lines=open("[Link]")
d=dict()
for line in lines:
words=[Link]().split(" ")
for word in words:
d[word]=[Link](word,0)+1

srtd=dict(sorted([Link](),key=[Link](1),reverse=True))
print(dict(list([Link]())[:10]))

[Link] file:

All that glitters is not gold


All is well
This is a well written story
All are invited

OUTPUT: {'All': 3, 'is': 3, 'well': 2, 'that': 1, 'glitters': 1, 'not': 1, 'gold': 1, 'This': 1, 'a': 1, 'written': 1}

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

fd=open("[Link]")
wfd=open("[Link]","w")
lines=[Link]()
print(lines)
[Link]()
print(lines)
for line in lines:
[Link](line)
[Link]()
[Link]()
OUTPUT:
[Link] file: [Link]

The quick brown The quick brown


fox fox
jumps over jumps over
the lazy dog
lazy dog the

Dept. of AIML, JNNCE, Shivamogga


[Link] 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.

from zipfile import ZipFile


import os

with ZipFile("[Link]","w") as zipob:


for folders,subfolders,files in [Link]('programs'):
for file in files:
file_path=[Link](folders,file)
[Link](file_path)
if [Link]("[Link]"):
print("Zip file created")
else:
print("Error in creation")
OUTPUT: ZIP file created

[Link] 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,b):
assert a>0,"give numerator >0"
if b==0:
raise Exception("Denominator cannot be zero")
c=a/b
return c

a=int(input('Enter a'))
b=int(input('Enter b'))
c=DivExp(a,b)
print(c)

OUTPUT: Enter a 10
Enter b 6
1.6666666666666667

Dept. of AIML, JNNCE, Shivamogga


[Link] a function which takes TWO objects representing complex numbers and returnsnew
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,real,imag):
[Link]=real
[Link]=imag

def __str__(self):
return str([Link])+"+i"+str([Link])
def add(c1,c2):
return Complex(([Link]+[Link]),([Link]+[Link]))

n=int(input("Enter N: "))
c=list()
for i in range(n):
real=int(input("Enter real: "))
imag=int(input("Enter imaginary: "))
[Link](Complex(real,imag))

print(c[0])
print(c[1])

sumc=c[0]
for i in range(1,n):
sumc=add(sumc,c[i])
print(sumc)

OUTPUT: Enter N4
Enter real 32
Enter imag-25
Enter real12
Enter imag -12
Enter real 45
Enter imag -32
Enter real 34
Enter imag -45
123+i-114

Dept. of AIML, JNNCE, Shivamogga


[Link] 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,

class Student:
def __init__(self,name,USN):
[Link]=name
[Link]=USN
[Link]=list()
def getmarks(self):
for i in range(3):
m=int(input("Enter marks: "))
[Link](m)
tot=sum([Link])
per=tot/3
[Link](tot)
[Link](per)
def display(self):
#print([Link])
#print([Link])
print([Link])

s1=Student("Arman","4JN22AI000")
[Link]()
[Link]()

OUTPUT:
Enter marks1 90
Enter marks2 89
Enter marks3 90
269 89.66666666666667

Dept. of AIML, JNNCE, Shivamogga

Common questions

Powered by AI

In Python, to determine if a person is a senior citizen, you need to calculate the person's age by subtracting their year of birth from the current year. If their age is 60 or more, they are considered a senior citizen. This involves using Python’s input function to capture the year of birth, and Python's datetime module to get the current year, then applying a simple age conditional check .

To compute a Fibonacci sequence of length N in Python, initialize the first two numbers of the sequence, typically 1 and 1. Then iterate from 0 to N, generating the subsequent Fibonacci numbers by summing the last two numbers in the sequence. This involves using a loop to iterate and update the sequence indices .

To compute a binomial coefficient in Python, first write a function to calculate the factorial of a number. Then use this function to compute the binomial coefficient using the formula: factorial(n) / (factorial(r) * factorial(n-r)). Input both N and R for this computation, and apply basic arithmetic operations within the factorial function .

Sorting the contents of a text file in Python involves opening the file and reading its lines into a list. You then apply the sort method to this list, and write the sorted lines to a new file. This requires using file methods such as open(), readlines(), and write(), along with list methods like sort() and strip() for line cleanup .

A Python program to read student details such as Name, USN, and Marks for three subjects can be constructed by taking input for each of these details and calculating the total marks by adding the three marks together. The percentage can then be calculated by dividing the total marks by the number of subjects, i.e., 3. This can be achieved using Python’s input function for data entry and basic arithmetic operations for calculations .

In Python, create a Student class with attributes for name, USN, and an empty list for marks. The __init__ method initializes the name and USN. The getmarks() method uses input to collect three subject marks and computes their sum and percentage, which are appended to the marks list. Finally, a display() method prints these details. Such encapsulation of functionality in methods is a demonstration of Object-Oriented Programming concepts .

To calculate the mean, variance, and standard deviation in Python, you start by reading N numbers into a list. Calculate the mean by dividing the sum of the list by its length. For variance, compute the average of squared deviations of each number from the mean. The standard deviation is the square root of this variance, which can be computed using Python's math module .

To display the frequency of each digit in a multi-digit number in Python, read the number as a string, convert each character to an integer, and increment the respective index in a list that tracks digit frequencies (initialized with zero for each digit 0-9). This involves looping over each character and using list indexing and updating operations .

Complex numbers can be added using Python by defining a class 'Complex' with real and imaginary attributes. A method for addition receives two complex objects and returns a new complex object with summed real and imaginary parts. Initialize the complex numbers using the class constructor and perform addition through an add() helper function .

To back up a folder into a ZIP file in Python, use the zipfile module. Start by walking through the directory using os.walk to gather file paths, and then use the ZipFile class to write each file into a ZIP archive. Check for the existence of the ZIP file to confirm successful backup .

You might also like