0% found this document useful (0 votes)
34 views32 pages

Python Lab Manual

The document is a lab manual for the Introduction to Python Programming course at Dr. H N National College of Engineering for the academic year 2024-25. It includes various programming exercises such as reading student details, checking senior citizen status, generating Fibonacci sequences, calculating factorials and binomial coefficients, and analyzing statistical measures like mean and variance. The manual emphasizes practical programming skills aligned with Outcome Based Education (OBE) and Choice Based Credit System (CBCS).

Uploaded by

sparkysanthosh69
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)
34 views32 pages

Python Lab Manual

The document is a lab manual for the Introduction to Python Programming course at Dr. H N National College of Engineering for the academic year 2024-25. It includes various programming exercises such as reading student details, checking senior citizen status, generating Fibonacci sequences, calculating factorials and binomial coefficients, and analyzing statistical measures like mean and variance. The manual emphasizes practical programming skills aligned with Outcome Based Education (OBE) and Choice Based Credit System (CBCS).

Uploaded by

sparkysanthosh69
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/ 32

Dr.

H N National College of Engineering


Approved by All India Council for Technical Education
(AICTE), Govt. of India and affiliated to Visvesvaraya
Technological University (VTU)
36B Cross, Jayanagar 7th block, Bangaluru – 560070

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

INTRODUCTION TO PYTHON PROGRAMMING LAB


BPLCK105B/205B – 1ST / 2ND SEMESTER B.E.

[AS PER OUTCOME BASED EDUCATION (OBE) AND CHOICE BASED


CREDIT SYSTEM (CBCS) 2022 SCHEME]

Academic Year – 2024-25

LAB MANUAL

Prepared by:
Dr. Suma Swamy
Professor
Dept. of CSE

Institute Vision and Mission

Our Vision
To impart perseverant education leading to greater heights

Our Mission
 By providing well-designed physical infrastructure with modern technology with a
supportive community
 By building resilience through self-awareness, stress management, and growth mindset
 By developing a sense of responsibility and accountability
 By developing empathy, integrity, self-reflection, and self-improvement

VALUES
Resilience, Reflection, Grit, Persistence and Determination
BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Department of CSE, Dr. HNNCE AY 2024-2025 1


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Department of CSE, Dr. HNNCE AY 2024-2025 2


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Department of CSE, Dr. HNNCE AY 2024-2025 3


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Manual

Question 1
a. Student Details
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.

stName = input("Enter the name of the student : ")


stUSN = input("Enter the USN of the student : ")
stMarks1 = int(input("Enter marks in Subject 1 : "))
stMarks2 = int(input("Enter marks in Subject 2 : "))
stMarks3 = int(input("Enter marks in Subject 3 : "))

print("Student Details\n=========================")
print("%12s"%("Name :"), stName)
print("%12s"%("USN :"), stUSN)
print("%12s"%("Marks 1 :"), stMarks1)
print("%12s"%("Marks 2 :"), stMarks2)
print("%12s"%("Marks 3 :"), stMarks3)
print("%12s"%("Total :"), stMarks1+stMarks2+stMarks3)
print("%12s"%("Percent :"), "%.2f"%((stMarks1+stMarks2+stMarks3)/3))
print("=========================")

Output:

Python 3.13.2 (tags/v3.13.2:4f8bb39, Feb 4 2025, 15:23:48) [MSC v.1942 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.

== RESTART: D:/2024-2025/EVEN/BPLCK205B Manual-New/student_details.py ==


Enter the name of the student : swati
Enter the USN of the student : 1HC24AD001
Enter marks in Subject 1 : 87
Enter marks in Subject 2 : 90
Enter marks in Subject 3 : 98
Student Details
=========================
Name : swati
USN : 1HC24AD001
Marks 1 : 87
Marks 2 : 90
Marks 3 : 98
Total : 275
Percent : 91.67

Department of CSE, Dr. HNNCE AY 2024-2025 4


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

b. Senior Citizen Check


Develop a program to read the name and year of birth of a person. Display whether the
person is a senior citizen or not.

from datetime import date

perName = input("Enter the name of the person : ")


perDOB = int(input("Enter his year of birth : "))

curYear = date.today().year
perAge = curYear - perDOB

if (perAge > 60):


print(perName, "aged", perAge, "years is a Senior Citizen.")
else:
print(perName, "aged", perAge, "years is not a Senior Citizen.")

Output:

== RESTART: D:/2024-2025/EVEN/BPLCK205B Manual-New/senior_citizen.py ==


Enter the name of the person : abhinav
Enter his year of birth : 2001
abhinav aged 24 years is not a Senior Citizen.
== RESTART: D:/2024-2025/EVEN/BPLCK205B Manual-New/senior_citizen.py ==
Enter the name of the person : shekhar
Enter his year of birth : 1942
shekhar aged 83 years is a Senior Citizen.

Department of CSE, Dr. HNNCE AY 2024-2025 5


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

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

num = int(input("Enter the Fibonacci sequence length to be generated : "))

firstTerm = 0
secondTerm = 1
print("The Fibonacci series with", num, "terms is :")
print(firstTerm, secondTerm, end=" ")
for i in range(2,num):
curTerm = firstTerm + secondTerm
print(curTerm, end=" ")
firstTerm = secondTerm
secondTerm = curTerm

Output:

== RESTART: D:/2024-2025/EVEN/BPLCK205B Manual-New /fibonacci_series.py =


Enter the Fibonacci sequence length to be generated : 6
The Fibonacci series with 6 terms is :
011235

Department of CSE, Dr. HNNCE AY 2024-2025 6


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

b. Factorial & Binomial Coefficient


Write a function to calculate factorial of a number. Develop a program to compute binomial
coefficient (Given N and R).

def fact(num):
if num == 0:
return 1
else:
return num * fact(num-1)

n = int(input("Enter the value of N : "))


r = int(input("Enter the value of R (R cannot be negative or greater than N): "))
nCr = fact(n)/(fact(r)*fact(n-r))

print(n,'C',r," = ","%d"%nCr,sep="")

Output:

== RESTART: D:/2024-2025/EVEN/BPLCK205B Manual-New /factorial-binomial-coeff.py


Enter the value of N : 10
Enter the value of R (R cannot be negative or greater than N): 5
10C5 = 252

Department of CSE, Dr. HNNCE AY 2024-2025 7


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Question 3
Mean, Variance and Standard Deviation
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

myList = []

num = int(input("Enter the number of elements in your list : "))

for i in range(num):
val = int(input("Enter the element : "))
myList.append(val)

print('The length of list1 is', len(myList))

print('List Contents', myList)

total = 0
for elem in myList:
total += elem

mean = total / num

total = 0
for elem in myList:
total += (elem - mean) * (elem - mean)

variance = total / num

stdDev = sqrt(variance)

print("Mean =", mean)


print("Variance =", variance)
print("Standard Deviation =", "%.2f"%stdDev)

Output:

=== == RESTART: D:/2024-2025/EVEN/BPLCK205B Manual-New /mean-variance-std-deviation.py


=====================================
Enter the number of elements in your list : 5
Enter the element : 1
Enter the element : 2
Enter the element : 3
Enter the element : 4
Enter the element : 5
The length of list1 is 5

Department of CSE, Dr. HNNCE AY 2024-2025 8


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

List Contents [1, 2, 3, 4, 5]


Mean = 3.0
Variance = 2.0
Standard Deviation = 1.41

Department of CSE, Dr. HNNCE AY 2024-2025 9


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Question 4
Digit Frequency
Read 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 : ")

print("The number entered is :", num)

uniqDig = set(num) #A set is a collection which is unordered and unindexed, and doesnt

# allow duplicates. In Python, sets are written with curly brackets. A list

# is a collection which is ordered and changeable(mutable).

print(uniqDig)

for elem in uniqDig:

print(elem, "occurs", num.count(elem), "times")

Output:

== RESTART: D:/2024-2025/EVEN/BPLCK205B Manual-New /digit-frequency.py


===========================================

Enter a number : 23345629115673

The number entered is : 23345629115673

{'7', '5', '4', '3', '1', '2', '9', '6'}

7 occurs 1 times

5 occurs 2 times

4 occurs 1 times

3 occurs 3 times

Department of CSE, Dr. HNNCE AY 2024-2025 10


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

1 occurs 2 times

2 occurs 2 times

9 occurs 1 times

6 occurs 2 times

Department of CSE, Dr. HNNCE AY 2024-2025 11


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Question 5
Word Frequency in a File
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]

Save the program file and text.txt file in


C:\Users\acer\AppData\Local\Programs\Python\Python313\

text.txt content:

How many lawyers does it take to change a light bulb?

Whereas the party of the first part, also known as "Lawyer", and the party of the second part, also
known as "Light Bulb", do hereby and forthwith agree to a transaction wherein the party of the
second part shall be removed from the current position as a result of failure to perform previously
agreed upon duties, i.e., the lighting, elucidation, and otherwise illumination of the area ranging
from the front (north) door, through the entryway, terminating at an area just inside the primary
living area, demarcated by the beginning of the carpet, any spillover illumination being at the
option of the party of the second part and not required by the aforementioned agreement between
the parties.

The aforementioned removal transaction shall include, but not be limited to, the following.
The party of the first part shall, with or without elevation at his option, by means of a chair,
stepstool, ladder or any other means of elevation, grasp the party of the second part and rotate the
party of the second part in a counter-clockwise direction, this point being tendered non-negotiable.
Upon reaching a point where the party of the second part becomes fully detached from the
receptacle, the party of the first part shall have the option of disposing of the party of the second
part in a manner consistent with all relevant and applicable local, state and federal statutes.

Once separation and disposal have been achieved, the party of the first part shall have the option of
beginning installation. Aforesaid installation shall occur in a manner consistent with the reverse of
the procedures described in step one of this self-same document, being careful to note that the
rotation should occur in a clockwise direction, this point also being non-negotiable.

The above described steps may be performed, at the option of the party of the first part, by any or
all agents authorized by him, the objective being to produce the most possible revenue for the
Partnership.

Don't read everything you believe.

Department of CSE, Dr. HNNCE AY 2024-2025 12


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

import sys
import string
import os.path

fname = input("Enter the filename : ") #sample file text.txt also provided

if not os.path.isfile(fname):

print("File", fname, "doesn't exists")

sys.exit(0)

infile = open(fname, "r")

filecontents = ""

for line in infile:

for ch in line:

if ch not in string.punctuation:

filecontents = filecontents + ch

else:

filecontents = filecontents + ' ' #replace punctuations and newline with a space

wordFreq = {}

wordList = filecontents.split()

#Calculate word Frequency

for word in wordList:

if word not in wordFreq.keys():

wordFreq[word] = 1

else:

Department of CSE, Dr. HNNCE AY 2024-2025 13


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

wordFreq[word] += 1

#Sort Dictionary based on values in descending order

sortedWordFreq = sorted(wordFreq.items(), key=lambda x:x[1], reverse=True )

#Display 10 most frequently appearing words with their count

print("\n===================================================")

print("10 most frequently appearing words with their count")

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

for i in range(10):

print(sortedWordFreq[i][0], "occurs", sortedWordFreq[i][1], "times")

Output:

======================================== RESTART:
C:/Users/acer/AppData/Local/Programs/Python/Python313/word-frequency.py
========================================

Enter the filename : text.txt

===================================================

10 most frequently appearing words with their count

===================================================

the occurs 45 times

of occurs 24 times

party occurs 12 times

part occurs 12 times

a occurs 9 times

and occurs 8 times

second occurs 7 times

Department of CSE, Dr. HNNCE AY 2024-2025 14


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

to occurs 6 times

shall occurs 6 times

first occurs 5 times

Department of CSE, Dr. HNNCE AY 2024-2025 15


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Question 6
Sort File Contents
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()].

unsorted.txt and program should be saved in


C:\Users\acer\AppData\Local\Programs\Python\Python313\

unsorted.txt contents:

It is so very hard to be an on-your-own-take-care-of-yourself-because-there-is-no-one-else-to-do-


it-for-you-grown-up.

Beware of a tall black man with one blond shoe.

To be or not to be.

What is the square root of 4b^2?

What do you call a principal female opera singer whose high C is lower than those of other
principal female opera singers?

A deep C diva.

A gift of a flower will soon be made to you.

Tuesday is the Wednesday of the rest of your life.

Knock, knock!

Who's there?

Sam and Janet.

Sam and Janet who?

Sam and Janet Evening...

You display the wonderful traits of charm and courtesy.

It were not best that we should all think alike; it is difference of opinion that makes horse-races.

Don't feed the bats tonight.

You have many friends and very few living enemies.

Department of CSE, Dr. HNNCE AY 2024-2025 16


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

How does a hacker fix a function which doesn't work for all of the elements in its domain?

He changes the domain.

All the troubles you have will pass away very quickly.

This life is yours. Some of it was given to you; the rest, you made yourself.

The surest protection against temptation is cowardice.

The man who sets out to carry a cat by its tail learns something that will always be useful and
which never will grow dim or doubtful.

Don't read everything you believe.

People are beginning to notice you. Try dressing before you leave the house.

Lay on, MacDuff, and curs'd be him who first cries, "Hold, enough!".

You may be recognized soon. Hide.

Exercise caution in your daily affairs.

Department of CSE, Dr. HNNCE AY 2024-2025 17


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

import os.path
import sys

fname = input("Enter the filename whose contents are to be sorted : ") #sample file unsorted.txt
#also provided

if not os.path.isfile(fname):

print("File", fname, "doesn't exists")

sys.exit(0)

infile = open(fname, "r")

myList = infile.readlines()

# print(myList)

#Remove trailing \n characters

lineList = []

for line in myList:

lineList.append(line.strip())

lineList.sort()

#Write sorted contents to new file sorted.txt

outfile = open("sorted.txt","w")

for line in lineList:

outfile.write(line + "\n")

Department of CSE, Dr. HNNCE AY 2024-2025 18


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

infile.close() # Close the input file

outfile.close() # Close the output file

if os.path.isfile("sorted.txt"):

print("\nFile containing sorted content sorted.txt created successfully")

print("sorted.txt contains", len(lineList), "lines")

print("Contents of sorted.txt")

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

rdFile = open("sorted.txt","r")

for line in rdFile:

print(line, end="")

Output:

====================================== RESTART:
C:/Users/acer/AppData/Local/Programs/Python/Python313/sortedfilecontents.py
======================

Enter the filename whose contents are to be sorted : unsorted.txt

File containing sorted content sorted.txt created successfully

sorted.txt contains 28 lines

Contents of sorted.txt

=================================================================

A deep C diva.

A gift of a flower will soon be made to you.

All the troubles you have will pass away very quickly.

Beware of a tall black man with one blond shoe.

Don't feed the bats tonight.

Department of CSE, Dr. HNNCE AY 2024-2025 19


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Don't read everything you believe.

Exercise caution in your daily affairs.

He changes the domain.

How does a hacker fix a function which doesn't work for all of the elements in its domain?

It is so very hard to be an on-your-own-take-care-of-yourself-because-there-is-no-one-else-to-do-


it-for-you-grown-up.

It were not best that we should all think alike; it is difference of opinion that makes horse-races.

Knock, knock!

Lay on, MacDuff, and curs'd be him who first cries, "Hold, enough!".

People are beginning to notice you. Try dressing before you leave the house.

Sam and Janet Evening...

Sam and Janet who?

Sam and Janet.

The man who sets out to carry a cat by its tail learns something that will always be useful and
which never will grow dim or doubtful.

The surest protection against temptation is cowardice.

This life is yours. Some of it was given to you; the rest, you made yourself.

To be or not to be.

Tuesday is the Wednesday of the rest of your life.

What do you call a principal female opera singer whose high C is lower than those of other
principal female opera singers?

What is the square root of 4b^2?

Who's there?

You display the wonderful traits of charm and courtesy.

You have many friends and very few living enemies.

You may be recognized soon. Hide.

Department of CSE, Dr. HNNCE AY 2024-2025 20


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Question 7
Backup Directory into Zip archive
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.

Create folder zipDemo in C:/Users/acer/AppData/Local/Programs/Python/Python313

which has 3 subfolders 1, 2, 3. Each of this subfolder has 1.1,1.2,2.1,2.2 and 3.1,3.2 subfolders.
In each subfolder we have a,b c,d e,f g,h i and j text files.

After executing the program, check the myZip.zip file in


C:/Users/acer/AppData/Local/Programs/Python/Python313

import os
import sys
import pathlib
import zipfile

dirName = input("Enter Directory name that you want to backup : ")

if not os.path.isdir(dirName):

print("Directory", dirName, "doesn't exists")

sys.exit(0)

curDirectory = pathlib.Path(dirName)

with zipfile.ZipFile("myZip.zip", mode="w") as archive:

for file_path in curDirectory.rglob("*"):

archive.write(file_path, arcname=file_path.relative_to(curDirectory))

if os.path.isfile("myZip.zip"):

print("Archive", "myZip.zip", "created successfully")

else:

print("Error in creating zip archive")

Department of CSE, Dr. HNNCE AY 2024-2025 21


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Output:

======================================= RESTART:
C:/Users/acer/AppData/Local/Programs/Python/Python313/zip-backup-folder.py
======================================

Enter Directory name that you want to backup : zipDemo

Archive myZip.zip created successfully

Department of CSE, Dr. HNNCE AY 2024-2025 22


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Question 8
Assertions and Exceptions Demo
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

def DivExp(a,b):

assert a>0, "a should be greater than 0"

try:

c = a/b

except ZeroDivisionError:

print("Value of b cannot be zero")

sys.exit(0)

else:

return c

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

val2 = int(input("Enter a value for b : "))

val3 = DivExp(val1, val2)

print(val1, "/", val2, "=", val3)

Department of CSE, Dr. HNNCE AY 2024-2025 23


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Output:
==================================== RESTART:
C:/Users/acer/AppData/Local/Programs/Python/Python313/AssertionExceptionDemo.py
====================================

Enter a value for a : 7

Enter a value for b : 6

7 / 6 = 1.1666666666666667

==================================== RESTART:
C:/Users/acer/AppData/Local/Programs/Python/Python313/AssertionExceptionDemo.py
====================================

Enter a value for a : 0

Enter a value for b : 5

Traceback (most recent call last):

File "C:/Users/acer/AppData/Local/Programs/Python/Python313/AssertionExceptionDemo.py",
line 16, in <module>

val3 = DivExp(val1, val2)

File "C:/Users/acer/AppData/Local/Programs/Python/Python313/AssertionExceptionDemo.py",
line 4, in DivExp

assert a>0, "a should be greater than 0"

AssertionError: a should be greater than 0

==================================== RESTART:
C:/Users/acer/AppData/Local/Programs/Python/Python313/AssertionExceptionDemo.py
====================================

Enter a value for a : -3

Enter a value for b : 5

Traceback (most recent call last):

File "C:/Users/acer/AppData/Local/Programs/Python/Python313/AssertionExceptionDemo.py",
line 16, in <module>

val3 = DivExp(val1, val2)

Department of CSE, Dr. HNNCE AY 2024-2025 24


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

File "C:/Users/acer/AppData/Local/Programs/Python/Python313/AssertionExceptionDemo.py",
line 4, in DivExp

assert a>0, "a should be greater than 0"

AssertionError: a should be greater than 0

==================================== RESTART:
C:/Users/acer/AppData/Local/Programs/Python/Python313/AssertionExceptionDemo.py
====================================

Enter a value for a : 6

Enter a value for b : 0

Value of b cannot be zero

Department of CSE, Dr. HNNCE AY 2024-2025 25


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Question 9
Complex Class Demo
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, realp = 0, imagp=0):

self.realp = realp

self.imagp = imagp

def setComplex(self, realp, imagp):

self.realp = realp

self.imagp = imagp

def readComplex(self):

self.realp = int(input("Enter the real part : "))

self.imagp = int(input("Enter the real part : "))

def showComplex(self):

print('(',self.realp,')','+i','(',self.imagp,')',sep="")

def addComplex(self, c2):

c3 = Complex()

Department of CSE, Dr. HNNCE AY 2024-2025 26


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

c3.realp = self.realp + c2.realp

c3.imagp = self.imagp + c2.imagp

return c3

def add2Complex(a,b):

c = a.addComplex(b)

return c

def main():

c1 = Complex(3,5)

c2 = Complex(6,4)

print("Complex Number 1")

c1.showComplex()

print("Complex Number 2")

c2.showComplex()

c3 = add2Complex(c1, c2)

print("Sum of two Complex Numbers")

c3.showComplex()

#Addition of N (N >=2) complex numbers

compList = []

num = int(input("\nEnter the value for N : "))

for i in range(num):

print("Object", i+1)

Department of CSE, Dr. HNNCE AY 2024-2025 27


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

obj = Complex()

obj.readComplex()

compList.append(obj)

print("\nEntered Complex numbers are : ")

for obj in compList:

obj.showComplex()

sumObj = Complex()

for obj in compList:

sumObj = add2Complex(sumObj, obj)

print("\nSum of N complex numbers is", end = " ")

sumObj.showComplex()

main()

Output:

==================================== RESTART:
C:/Users/acer/AppData/Local/Programs/Python/Python313/addcomplexnumbers-class.py
===================================

Complex Number 1

(3)+i(5)

Complex Number 2

(6)+i(4)

Sum of two Complex Numbers

(9)+i(9)

Department of CSE, Dr. HNNCE AY 2024-2025 28


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

Enter the value for N : 5

Object 1

Enter the real part : 2

Enter the real part : 5

Object 2

Enter the real part : 3

Enter the real part : 7

Object 3

Enter the real part : 5

Enter the real part : 7

Object 4

Enter the real part : 8

Enter the real part : 9

Object 5

Enter the real part : 1

Enter the real part : 9

Entered Complex numbers are :

(2)+i(5)

(3)+i(7)

(5)+i(7)

(8)+i(9)

(1)+i(9)

Sum of N complex numbers is (19)+i(37)

Department of CSE, Dr. HNNCE AY 2024-2025 29


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

10. Student Class Demo


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, name = "", usn = "", score = [0,0,0,0]):

self.name = name

self.usn = usn

self.score = score

def getMarks(self):

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

self.usn = input("Enter student USN : ")

self.score[0] = int(input("Enter marks in Subject 1 : "))

self.score[1] = int(input("Enter marks in Subject 2 : "))

self.score[2] = int(input("Enter marks in Subject 3 : "))

self.score[3] = self.score[0] + self.score[1] + self.score[2]

def display(self):

percentage = self.score[3]/3

spcstr = "=" * 81

print(spcstr)

print("SCORE CARD DETAILS".center(81))

print(spcstr)

Department of CSE, Dr. HNNCE AY 2024-2025 30


BPLCK105B/205B – Introduction to Python Programming Laboratory Manual

print("%15s"%("NAME"), "%12s"%("USN"),
"%8s"%"MARKS1","%8s"%"MARKS2","%8s"%"MARKS3","%8s"%"TOTAL","%12s"%("PER
CENTAGE"))

print(spcstr)

print("%15s"%self.name, "%12s"%self.usn,
"%8d"%self.score[0],"%8d"%self.score[1],"%8d"%self.score[2],"%8d"%self.score[3],"%12.2f"%
percentage)

print(spcstr)

def main():

s1 = Student()

s1.getMarks()

s1.display()

main()

Output:
========================================= RESTART:
C:/Users/acer/AppData/Local/Programs/Python/Python313/student-class.py
========================================

Enter student Name : sanniddhi

Enter student USN : 1HC24IS004

Enter marks in Subject 1 : 87

Enter marks in Subject 2 : 90

Enter marks in Subject 3 : 84

=====================================================================
SCORE CARD DETAILS
=====================================================================
NAME USN MARKS1 MARKS2 MARKS3 TOTAL PERCENTAGE
=====================================================================
sanniddhi 1HC24IS004 87 90 84 261 87.00
=====================================================================

Department of CSE, Dr. HNNCE AY 2024-2025 31

You might also like