0% found this document useful (0 votes)
2K views25 pages

BPLCK205B Manual (23-24)

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)
2K views25 pages

BPLCK205B Manual (23-24)

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/ 25

HKBK COLLEGE OF ENGINEERING

(Affiliated to VTU, Belgaum and Approved by AICTE)


BANGALORE -560045
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Introduction to Python Programming Laboratory


BPLCK205B
As per VTU - Choice Based Credit System – 22 Scheme
(Academic year: 2023 -2024)
2nd Semester CSE

LABORATORY MANUAL

Prepared By
Dr. DEEPAK NR
Prof LIJIMOL K
Prof MINAL K
Prof JULIET JOHNY

Verified By
DQAC HOD

1|Page
HKBK COLLEGE OF ENGINEERING
(Affiliated to VTU, Belgaum and Approved by AICTE)
BANGALORE -560045
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Vision and Mission of the Institution


Vision
To empower students through wholesome education and enable the students to develop into
highly qualified and trained professionals with ethics and emerge as responsible citizens with a
broad outlook to build a vibrant nation.

Mission
M1. To achieve academic excellence in science, engineering, and technology through
dedication to duty, innovation in teaching, and faith in human values.

M2. To enable our students to develop into outstanding professionals with high ethical
standards to face the challenges of the 21st century.

M3. To provide educational opportunities to the deprived and weaker section of


society to uplift their socioeconomic status.

Vision and Mission of the CSE Department

Vision
To advance the intellectual capacity of the nation and the international community by imparting
knowledge to graduates who are globally recognized as innovators, entrepreneurs and
competent professionals.

Mission
M1. To provide excellent technical knowledge and computing skills to make the
graduates globally competitive with professional ethics.

M2. To involve in research activities and be committed to lifelong learning to make


positive contributions to the society

2|Page
HKBK COLLEGE OF ENGINEERING
(Affiliated to VTU, Belgaum and Approved by AICTE)
DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Program Outcomes (PO’s) / Graduate Attributes (GA)


PO1 Engineering Knowledge: Apply knowledge of mathematics, science, engineering
fundamentals and an engineering specialization to the solution of complex
engineering problems.
PO2 Problem Analysis: Identity, formulate, research literature and analyze complex
engineering problems reaching substantiated conclusions using the first principles
of mathematics, natural sciences and engineering sciences
PO3 Design/ Development of Solutions: Design solutions for complex engineering
problems and design system components or processes that meet specified needs with
appropriate consideration for public health and safety, a n d cultural, societal and
environmental considerations.
PO4 Conduct investigations of complex problems using research-based knowledge
and research methods including design of experiments, analysis, and interpretation
of data, and synthesis of the information to provide valid conclusions.
PO5 Modern Tool Usage: Create, select and apply appropriate techniques, resources and
modern engineering and IT tools including prediction and modelling to complex
engineering activities with an under- standing of the limitations.
PO6 The Engineer and Society: Apply reasoning informed by the contextual knowledge
to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to professional engineering practice.
PO7 Environment and Sustainability: Understand the impact of professional
engineering solutions in societal and environmental contexts and demonstrate
knowledge of and need for sustainable development.
PO8 Ethics: Apply ethical principles and commit to professional ethics and
responsibilities and norms of engineering practice.
PO9 Individual and Team Work: Function effectively as an individual, and as a
member or leader in diverse teams and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as being able to
comprehend and write effective reports and design documentation, make effective
presentations and give and receive clear instructions.

3|Page
PO11 Project Management and Finance: Demonstrate knowledge and understanding of
engineering and management principles and apply these to one’s own work, as a
member and leader in a team, to manage projects and in multidisciplinary
environments.
PO12 Life-long Learning: Recognize the need for and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.

Program Specific Outcomes (PSO’s)

PSO1 Problem-Solving Skills: An ability to investigate and solve a problem by


analysis, interpretation of data, design, and implementation through
appropriate techniques, tools, and skills.
PSO2 Professional Skills: An ability to apply algorithmic principles, computing
skills and computer science theory in the modelling and design of computer-
based systems.
PSO3 Entrepreneurial Ability: An ability to apply design, development principles, and
management skills in the construction of software products of varying complexity to
become an entrepreneur

Programme Educational Objectives (PEO’s)

PEO-1 To provide students with a strong foundation in engineering fundamentals and in


the computer science and engineering to work in the global scenario.
PEO-2 To provide a sound knowledge of programming and computing techniques
and good communication and interpersonal skills so that they will be capable of
analysing, designing, and building innovative software systems.
PEO-3 To equip students in their chosen field of engineering and related fields to enable
them to work in multidisciplinary teams.
PEO-4 To inculcate in students professional, personal, and ethical attitudes to relate
engineering issues to broader social context and become a responsible citizens.
PEO-5 To provide students with an environment for life-long learning which allows them
to successfully adapt to the evolving technologies throughout their professional
carrier and face global challenges.

Course outcome (Course Skill Set)

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.

4|Page
Mapping of Course Outcomes to Program Outcomes

PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2 PSO3
CO1 2 1 1 1 2 1 1 1
CO2 3 2 1 2 3 3 2 3
CO3 2 1 1 1 2 1 1 2
CO4 2 1 1 1 2 1 1 2
CO5
AVG 2.2 1.2 1 1.2 2.2 1 0.2 0.5 1.2 1.7

3 High 2 Moderate 1 Low _ No Correlation

INTRODUCTION TO PYTHON
PROGRAMMING
(Effective from the academic year 2022 -2023)
SEMESTER – II
Course Code BPLCK205B CIE Marks 50
SEE Marks 50
Course Type (Theory/Practical /Integrated ) Integrated
Total Marks 100
Teaching Hours/Week (L:T:P: S0029 2:0:2:0 Exam Hours 03
Total Hours of Pedagogy 40 hours Credits 03
Course Learning Objectives: This course (BPLCK205B) will enable students to:
 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.
Descriptions (if any):

Programs List:
1. a. Develop a program to read the student details like Name, USN, and Marks in three subjects.
Displaythe 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
binomialcoefficient (Given N and R).
3. Read N numbers from the console and create a list. Develop a program to print mean, variance
andstandard deviation with suitable messages.
4. Read a multi-digit number (as chars) from the console. Develop a program to print
thefrequency 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
offrequency 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()].

5|Page
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.]
Laboratory Outcomes: The student should be able to:
 These are sample Strategies, which teacher can use to accelerate the attainment of the various
course outcomes and make Teaching –Learning more effective
 Use https://pythontutor.com/visualize.html#mode=edit in order to visualize the python code
 Demonstrate and visualize basic data types (list, tuple, dictionary).
 Chalk and talk
 online and videos
Assessment Details (both CIE and SEE):
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.

Continuous Internal Evaluation (CIE):


The CIE marks for the theory component of the IC shall be 30 marks and for the
laboratorycomponent 20 Marks.
CIE for the theory component of the IC

 Three Tests each of 20 Marks; after the completion of the syllabus of 35-40%, 65- 70%,and
90-100% respectively
 Two Assignments/two quizzes/ seminars/one field survey and report presentation/one course
project totalling 20 marks.
Total Marks scored (test + assignments) out of 80 shall be scaled down to 30 marks 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 05marks 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

6|Page
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.

Semester End Examination (SEE):


SEE for IC
Theory SEE will be conducted by University as per the scheduled time table, with common questionpapers
for the course (duration 03 hours)
1. The question paper will have ten questions. Each question is set for 20 marks.
2. There will be 2 questions from each module. Each of the two questions under a module (with a
maximum of 3 sub-questions), should have a mix of topics under that module.
3. The students have to answer 5 full questions, selecting one full question from each module.

The theory portion of the Integrated Course shall be for both CIE and SEE, whereas the practical
portion will have a CIE component only. Questions mentioned in the SEE paper shallinclude
questions from the practical component).

Passing standard:
 The minimum marks to be secured in CIE to appear for SEE shall be 12 (40% of maximum marks-
30) in the theory component and 08 (40% of maximum marks -20) in the practical component. The
laboratory component of the IPCC shall be for CIE only. However, in SEE, the questions from the
laboratory component shall be included. The maximum of 04/05 questions to be set from the
practical component of IPCC, the total marks of all questions should not be more than 30 marks.

SEE will be conducted for 100 marks and students shall secure 35% of the maximum marksto qualify for
the SEE. Marks secured will be scaled down to 50.

Content beyond Syllabus:


Create a NumPy program to compute the matrix multiplication of two given arrays.

7|Page
Program 1
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.
Program: studentname = input('Enter the Name of the student: ')
usn = input('Enter the USN of the student: ')
m1 = int(input('Enter the mark in first subject: '))
m2 = int(input('Enter the mark in second subject: '))
m3 = int(input('Enter the mark in third subject: '))
total = m1+m2+m3
percentage = round((total/300)*100)
print('\nName of the Student: ', studentname)
print('USN: ', usn) print('Mark in Subject 1: ', m1)
print('Mark in Subject 2: ', m2)
print('Mark in Subject 3: ', m3)
print('Total Score = ', total)
print('Percentage = ', percentage)
if percentage >=90:
print('First Class Exemplary.')
elif percentage >=75 and percentage <90:
print('First Class with Distinction.')
elif percentage >=60 and percentage <75:
print('First Class.')
elif percentage >=35 and percentage <60:
print('Second Class.')
else:
print('Fail.')

Output :

Enter the Name of the student: Tanishk Kumar


Enter the USN of the student: 1HK22IS007
Enter the mark in first subject: 80
Enter the mark in second subject: 90
Enter the mark in third subject: 80
Name of the Student: Tanishk Kumar
USN: 1HK22IS007
Mark in Subject 1: 80
Mark in Subject 2: 90
Mark in Subject 3: 80
Total Score = 250
Percentage = 83
First Class with Distinction.

8|Page
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. Program: personname = input('Enter the Name of
the person: ') yearofbirth = int(input('Enter the Year of Birth: ')) currentyear = 2023
age = currentyear - yearofbirth print('\nName of the person: ', personname) print('Year
of Birth of the person: ', yearofbirth) print('Age of the person: ', age) if age >= 60:
print('The person is a Senior Citizen.') else: print('The person is not a Senior Citizen.')

Program

personname = input('Enter the Name of the person: ')


yearofbirth = int(input('Enter the Year of Birth: '))
currentyear = 2023
age = currentyear - yearofbirth
print('\nName of the person: ', personname)
print('Year of Birth of the person: ', yearofbirth)
print('Age of the person: ', age)
if age >= 60:
print('The person is a Senior Citizen.')
else:
print('The person is not a Senior Citizen.')

Output:
Enter the Name of the person: Tanuj Kumar
Enter the Year of Birth: 2006

Name of the person: Tanuj Kumar


Year of Birth of the person: 2006
Age of the person: 17
The person is not a Senior Citizen.

9|Page
2.a. Develop a program to generate Fibonacci sequence of length (N). Read N from the
console.
Program:

f0 = 0
f1 = 1
num = int(input('Enter the Length of required Fibonacci Sequence: '))
if N<=0:
print('Enter Positive Integer value: ')
else:
i=0
print('Fibonacci Sequence for N = '+ str(num) + ' is: ')
while i<num:
print(f0)
fth = f0 + f1
f0 = f1
f1 = fth
i += 1
Output:
Enter the Length of required Fibonacci Sequence: 10
Fibonacci Sequence for N = 10 is:
0
1
1
2
3
5
8
13
21
34
Enter the Number to find factorial: 5
The Factorial of 5 is 120

10 | P a g e
2. b. Write a function to calculate factorial of a number. Develop a program to compute
binomial coefficient (Given N and R)

Factorial of a Number:

Program:

def factorial(N):
if N<0:
print('Enter the positive integer')
elif N==0:
print('The Factorial of 0 is 1')
elif N==1:
print('The Factorial of 1 is 1')
else:
i=1
f1=1
while i<=N:
fth=f1*i
f1=fth
i+=1
return fth
N=int(input('Enter the Number to find factorial: '))
fact = factorial(N)
print('The Factorial of ' +str(N)+ ' is ', fact)

Output:

Enter the Number to find factorial: 5


The Factorial of 5 is 120

Binomial coefficient:

Program:

def factorial(N):
if N<0:
print('Enter the positive integer')
elif N==0:
print('The Factorial of 0 is 1')
elif N==1:
print('The Factorial of 1 is 1')
else:
i=1
f1=1
while i<=N:
fth=f1*i
f1=fth
i+=1
return fth
N=int(input('Enter the value of N: '))
R=int(input('Enter the value of R '))

11 | P a g e
factN = factorial(N)
factR = factorial(R)
binomial = factN / (factR*factorial(N-R))
print('The Binomial coefficient for N= ' +str(N)+ ' and R= '+str(R)+ ' is', binomial)

Output:

Enter the value of N: 7


Enter the value of R 3
The Binomial coefficient for N= 7 and R= 3 is 35.0

12 | P a g e
3. Read N numbers from the console and create a list. Develop a program to print mean,
Variance and standard deviation with suitable messages.

Program:

N=int(input('Enter the number of elements: '))


lis=[]
for i in range(N):
lis.append(int(input('Enter the element: ')))
mean = round(sum(lis)/N,2)
print('\nMean is ',mean)
lis_mean=[]
for i in range(N):
lis_mean.append((lis[i] - mean)**2)
variance = round(sum(lis_mean)/N,2)
print('Variance is ', variance)
SD=round(variance**(1/2),2)
print('Standard deviation is ', SD)
if SD>=1.5:
print('High Dispersion, Low Reliability.')
else:
print('Low Dispersion, Reliable.')

Output:

Enter the number of elements: 5


Enter the element: 10
Enter the element: 20
Enter the element: 30
Enter the element: 40
Enter the element: 50
Mean is 30.0
Variance is 200.0
Standard deviation is 14.14
High Dispersion, Low Reliability.

13 | P a g e
4. Read a multi-digit number (as chars) from the console. Develop a program to print
the frequency of each digit with suitable message.

Program:

import pprint
message = input('Enter your input: ')
count = {}
for character in message:
count.setdefault(character, 0)
count[character] = count[character] + 1
print('Frequency of words appeared in the Sentence or paragraph\n')
pprint.pprint(count)
print()
for k,v in count.items():
print('Character \''+str(k)+'\' appeared ' + str(v)+ ' times')

Output:
Enter your input: When he began implementing Python, Guido van Rossum was
also reading the published scripts from “Monty Python's Flying Circus”, a
BBC comedy series from the 1970s. Van Rossum thought he needed a name that
was short, unique, and slightly mysterious, so he decided to call the
language Python.
Frequency of words appeared in the Sentence or paragraph
{' ': 47,
"'": 1,
',': 5,
'.': 2,
'0': 1,
'1': 1,
'7': 1,
'9': 1,
'B': 2,
'C': 2,
'F': 1,
'G': 1,
'M': 1,
'P': 3,
'R': 2,
'V': 1,
'W': 1,
'a': 15,
'b': 2,
'c': 5,

14 | P a g e
'd': 10,
'e': 24,
'f': 2,
'g': 8,
'h': 16,
'i': 13,
'l': 9,
'm': 9,
'n': 17,
'o': 16,
'p': 3,
'q': 1,
'r': 8,
's': 20,
't': 17,
'u': 10,
'v': 1,
'w': 2,
'y': 8,
'“': 1,
'”': 1}
Character 'W' appeared 1 times
Character 'h' appeared 16 times
Character 'e' appeared 24 times
Character 'n' appeared 17 times
Character ' ' appeared 47 times
Character 'b' appeared 2 times
Character 'g' appeared 8 times
Character 'a' appeared 15 times
Character 'i' appeared 13 times
Character 'm' appeared 9 times
Character 'p' appeared 3 times
Character 'l' appeared 9 times
Character 't' appeared 17 times
Character 'P' appeared 3 times
Character 'y' appeared 8 times
Character 'o' appeared 16 times
Character ',' appeared 5 times
Character 'G' appeared 1 times
Character 'u' appeared 10 times
Character 'd' appeared 10 times
Character 'v' appeared 1 times
Character 'R' appeared 2 times
Character 's' appeared 20 times

15 | P a g e
Character 'w' appeared 2 times
Character 'r' appeared 8 times
Character 'c' appeared 5 times
Character 'f' appeared 2 times
Character '“' appeared 1 times
Character 'M' appeared 1 times
Character ''' appeared 1 times
Character 'F' appeared 1 times
Character 'C' appeared 2 times
Character '”' appeared 1 times
Character 'B' appeared 2 times
Character '1' appeared 1 times
Character '9' appeared 1 times
Character '7' appeared 1 times
Character '0' appeared 1 times
Character '.' appeared 2 times
Character 'V' appeared 1 times
Character 'q' appeared 1 times

16 | P a g e
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]

Before starting the program save some content in .txt file, and use the path for the same file in
message1=open(“PATH”)

Program:

import pprint
message1 =open(r"D:\Sharavana\AY-2022-23[ODD]\shara.txt")
message = message1.read()
message1.close()
print('The content in the file is: \n\n', message)
count = {}
for character in message.split():
count.setdefault(character, 0)
count[character] = count[character] + 1
print('\nFrequency of words appeared in the Sentence or paragraph\n')
pprint.pprint(count)
print()
sortedcount = sorted(count.items(), key=lambda x:x[1], reverse=True)
converttodict = dict(sortedcount)
print('\nSorted in descending order:\n\n',converttodict)
import itertools
sliceddict = dict(itertools.islice(converttodict.items(), 10))
print('\nTen Most frequently appeared word in a paragraph :\n\n',sliceddict)

Output:

The content in the file is:


Frequency of words appeared in the Sentence or paragraph
Sorted in descending order:

17 | P a g e
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()].

Program:
namelist=open(r’D:\Sharavana\AY-2022-23[ODD]\namelist.txt’)
namelist1=namelist.readlines()
namelist.close()
print('\n\n content available of the file is:\n\n',namelist1)
namelist1.sort()
sortedlist2=open(r’D:\Sharavana\AY-2022-23[ODD]\sortedlist.txt','w')
sortedlist2.writelines(namelist1)
sortedlist2.close()
print('\n\n Sorted content is :\n\n',namelist1)

Output:
content available of the file is:

Sorted content is :

18 | P a g e
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.

Program:

import zipfile, os
def backupToZip(folder):
folder = os.path.abspath(folder)
number = 1
while True:
zipFilename = os.path.basename(folder) + '_' + str(number) + '.zip'
if not os.path.exists(zipFilename):
break
number = number + 1
print('Creating %s...' % (zipFilename))
backupZip = zipfile.ZipFile(zipFilename, 'w')
for foldername, subfolders, filenames in os.walk(folder):
print('Adding files in %s...' % (foldername))
backupZip.write(foldername)
for filename in filenames:
newBase = os.path.basename(folder)
if filename.startswith(newBase) and filename.endswith('.zip'):
continue
backupZip.write(os.path.join(foldername, filename))
backupZip.close()
print('Done.')
# Main Program
backupToZip(r'C:\Users\Tanishk\Desktop\bb')

Output:

Done

19 | P a g e
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.

Program:

def DivExp(a, b):


assert a > 0, "a should be greater than 0"
if b == 0:
raise Exception("b can't be zero")
c=a/b
return c
a = float(input("Enter a value for a: "))
b = float(input("Enter a value for b: "))
try:
result = DivExp(a, b)
except Exception as e:
print("Error: %s"%e)
else:
print("The result of %s/%s is %s" %(a,b,result))

Output:

Enter a value for a: 3


Enter a value for b: 0

Error: b can't be zero


Enter a value for a: 0
Enter a value for b: 5
Error: a should be greater than 0

Enter a value for a: 3


Enter a value for b: 1
The result of 3.0/1.0 is 3.0

20 | P a g e
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.

Program:

class Complex:
def init (self, real, imag):
self.real = real
self.imag = imag
def add (self, other):
return Complex(self.real + other.real, self.imag + other.imag)
def str (self):
if self.imag >= 0:
return f"{self.real}+{self.imag}i"
else:
return f"{self.real}{self.imag}i"
def add_complex_numbers(num1, num2):
return num1 + num2
n = int(input("Enter the number of complex numbers: "))
complex_numbers = []
for i in range(n):
real, imag = input(f"Enter complex number {i+1}: ").split()
complex_numbers.append(Complex(float(real), float(imag)))
result = complex_numbers[0]
for i in range(1, n):
result = add_complex_numbers(result, complex_numbers[i])
print("Sum of the complex numbers is:", result)

Output:
Enter the number of complex numbers: 2
Enter complex number 1: 1 2
Enter complex number 2: 1 2
Sum of the complex numbers is: 2.0+4.0i

21 | P a g e
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.]

Program:

class Student:
def init (self, name, usn):
self.name = name
self.usn = usn
self.marks = []
self.total = 0
def getMarks(self):
for i in range(3):
marks = float(input(f"Enter marks for subject {i+1}: "))
self.marks.append(marks)
self.total += marks
def display(self):
print("Name:", self.name)
print("USN:", self.usn)
print("Marks:")
for i in range(3):
print(f"\tSubject {i+1}: {self.marks[i]}")
print("Total:", self.total)
print("Percentage:", round((self.total / 3),2))
# Main program
name = input("Enter name: ")
usn = input("Enter USN: ")
student = Student(name, usn)
student.getMarks()
student.display()

22 | P a g e
Output:
Enter name: Kumar
Enter USN: 1HK22IS001
Enter marks for subject 1: 30
Enter marks for subject 2: 30
Enter marks for subject 3: 20
Name: Kumar
USN: 1HK22IS001
Marks:
Subject 1: 30.0
Subject 2: 30.0
Subject 3: 20.0
Total: 80.0
Percentage: 26.67

23 | P a g e
Content beyond Syllabus:
Create a NumPy program to compute the matrix multiplication of two given arrays.

import numpy as np

matrix1 = np.array([[1, 2, 3],


[4, 5, 6],
[7, 8, 9]])

matrix2 = np.array([[9, 8, 7],


[6, 5, 4],
[3, 2, 1]])

result = np.matmul(matrix1, matrix2)

print("Matrix Multiplication Result:")


print(result)

24 | P a g e
Viva Questions:
1. Explain the difference between a list and a tuple in Python.

2. What is the purpose of the range() function in Python?

3. How do you check the length of a string in Python?

4. What is the purpose of the append() method in Python lists?

5. Explain the difference between a function and a method in Python.

6. What is the output of the following code snippet: print(3 * 2 ** 3)?

7. How do you convert a string to lowercase in Python?

8. What does the % operator do in Python?

9. What is the purpose of the pass statement in Python?

10. Explain the difference between a local variable and a global variable in Python.

11. What is the output of the following code snippet: print(type(42.0))?

12. How do you check if a key exists in a dictionary in Python?

13. What is the purpose of the import statement in Python?

14. Explain the concept of a lambda function in Python.

25 | P a g e

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy