22PLC15Bset2 (1) - 1
22PLC15Bset2 (1) - 1
Note: 01. Answer any FIVE full questions, choosing at least ONE question from each MODULE.
*Bloom’s
m
Module -1 Taxonomy Marks
Level
Q.01 a With Python programming examples to each, explain the syntax and
L2 08
control flow diagrams of break and continue statements.
co
Python break is used to terminate the execution of the loop.
e.
dg
i=1
ue
while i < 6:
print(i)
if i == 3:
break
i += 1
OUTPUT
1
vt
2
3
Python Continue Statement skips the execution of the program block from
after the continue statement and forces the control to start the next iteration.
Page 01 of 02
22PLC15B
m
i=0
while i <= 20 :
i += 1 #i=i+1
if i % 2 == 1 :
co
continue
print(i)
OUTPUT:
2
4
6 e.
8
10
12
14
16
dg
18
20
b Explain TWO ways of importing modules into application in Python
L2 06
with
syntax and suitable programming examples.
ue
1. 1.
2. import module_name: This statement imports the entire module and allows you
to use its functions, classes, and variables with the module_name. prefix. For
vt
example:
import math
print(math.pi)
2. 2.
3. from module_name import function_name: This statement imports a specific
function from a module and allows you to use it without the module_name.
prefix. For example:
3. 3.
4. import module_name as alias_name: This statement imports a module and gives
it an alias name to use in the program. For example:
import numpy as np
Page 02 of 02
22PLC15B
arr = np.array([1, 2, 3])
4. 4.
from module_name import *: This statement imports all functions, classes, and
variables from a module into the program's namespace. However, this method
is generally discouraged because it can lead to naming conflicts and make the
code harder to read and understand.
c Write a function to calculate factorial of a number. Develop a program to
L3 06
compute binomialcoefficient (Given N and R).
m
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
co
print("The factorial of",num,"is",factorial)
OUTPUT:
Enter a number: 4
The factorial of 4 is 24
OR
Q.02 a Explain looping control statements in Python with a syntax and
L2 06
example to e.
each.
Looping means repeating something over and over until a particular condition
is satisfied.
dg
Python has two primitive loop commands:
while loops
for loops
The while Loop
With the while loop we can execute a set of statements as long as a condition is
true.
ue
i=1
while i < 6:
print(i)
i += 1
OUTPUT:
1
2
vt
3
4
5
for Loops and the range() Function The while loop keeps looping while its
condition is True, but what if you want to execute a block of code only a certain
number of times. You can do this with a for loop statement and the range()
function. For loop includes the following:
The for keyword
A variable name
The in keyword
A call to the range() method with up to three integers passed to it
A colon
Starting on the next line, an indented block of code
Example:
print('My name is')
for i in range(3):
Page 03 of 02
22PLC15B
print('Jimmy Three Times ')
OUTPUT:
Jimmy Three Times
Jimmy Three Times
Jimmy Three Times
nterms = int(input ("How many terms the user wants to print? "))
# First two terms
n1 = 0
n2 = 1
m
count = 0
# Now, we will check if the number of terms is valid or not
if nterms <= 0:
print ("Please enter a positive integer, the given number is not valid")
# if there is only one term, it will return n_1
co
elif nterms == 1:
print ("The Fibonacci sequence of the numbers up to", nterms, ": ")
print(n1)
# Then we will generate Fibonacci sequence of number
else:
print ("The fibonacci sequence of the numbers is:")
while count < nterms: e.
print(n1)
nth = n1 + n2
# At last, we will update values
n1 = n2
n2 = nth
dg
count += 1
OUTPUT
How many terms the user wants to print? 8
The fibonacci sequence of the numbers is:
0
1
ue
1
2
3
5
8
13
c Write a function named DivExp which takes TWO parameters a, b and
vt
def DivExp(a,b):
try:
c=a/b
return(c)
except:
print(“divide by zero error”)
m
1. Global scope: Variables defined outside any function or class have a global
scope. These variables can be accessed or modified from anywhere in the
program.
Example of global variable:
x = 300 Global Variable
co
def myfunc():
print(x)
myfunc()
print(x)
OUTPUT
300
2.
3.
300 e.
Local scope: Variables defined inside a function have a local scope. These
variables can only be accessed or modified within the function in which they
are defined. Local variables take precedence over global variables with the
same name.
dg
Example of local variable:
def myfunc():
x = 300 Local variable
print(x)
myfunc()
OUTPUT
300
4.
ue
Module-2
Q. 03 a Explain with a programming example to each:
(ii) get() L2 06
(iii) setdefault()
(i) get(): The get() method in Python is used to access the value of a key in a
dictionary. It takes one mandatory argument, which is the key to be searched in
the dictionary.
# create a dictionary
my_dict = {'apple': 10, 'banana': 20, 'orange': 30}
# Output: 10
# create a dictionary
my_dict = {'apple': 10, 'banana': 20, 'orange': 30}
m
mango_count = my_dict.setdefault('mango', 40)
co
print(my_dict)
b
and copy.deepcopy( ) methods.
e.
Develop suitable Python programs with nested lists to explain copy.copy( )
L3 08
copy.copy() and copy.deepcopy() are methods from the Python copy module
used for creating copies of objects. Both of these methods can be used with
dg
nested lists.
Using copy.copy()
copy.copy() creates a shallow copy of an object. This means that a new object
is created which is a copy of the original object, but the references to the
objects inside the original object are not copied. Instead, the new object
ue
import copy
original_list=[[1,2,3],[4,5,6],[7,8,9]]
# create a shallow copy of original_list
shallow_copy = copy.copy(original_list)
vt
# Output:
[[100, 2, 3], [4, 5, 6], [7, 8, 9]]
[[100, 2, 3], [4, 5, 6], [7, 8, 9]]
Using copy.deepcopy()
copy.deepcopy() creates a deep copy of an object. This means that a new
object is created which is a copy of the original object, and the references to the
Page 06 of 02
22PLC15B
objects inside the original object are also copied. This creates a completely new
set of objects, independent of the original object.
import copy
original_list=[[1,2,3],[4,5,6],[7,8,9]]
# create a deep copy of original_list
deep_copy = copy.deepcopy(original_list)
m
print(deep_copy)
# Output:
[[100, 2, 3], [4, 5, 6], [7, 8, 9]]
[[200, 2, 3], [4, 5, 6], [7, 8, 9]]
c Explain append() and index() functions with respect to lists in Python. L2 06
co
append() and index() are two built-in functions in Python that are used with
lists.
1. append() function:
The append() function is used to add an element to the end of a list. The
example for append() function is as follows:
ls=[1,2,3]
ls.append("hi")
ls.append(10)
e.
print(ls)
dg
OUTPUT: [1, 2, 3, “hi”, 10]
2. index() function:
The index() function is used to find the index of a specified element in a list.
ue
OUTPUT:
1
As we can see, the index variable now contains the index of the "banana"
element in the fruits list, which is 1.
OR
Q.04 a Explain different ways to delete an element from a list with suitable Python
L2 10
syntax and programming examples.
pop(): This method deletes the last element in the list, by default.
ls=[3,6,-2,8,10]
x=ls.pop()
print(ls)
ls=[3,6,-2,8,10]
del ls[2]
print(ls)
OUTPUT : [3, 6, 8, 10]
clear(): This method removes all the elements in the list and makes
the list empty.
ls=[1,2,3]
ls.clear()
print(ls)
m
You can use the remove() method to remove an element from a list by
specifying its value. Here's an example:
my_list = [1, 2, 3, 4, 5]
my_list.remove(3)
print(my_list) # Output: [1, 2, 4, 5]
co
b Read a multi-digit number (as chars) from the console. Develop a program
L3 06
to print the frequency of each digit with suitable message.
The tuple data type is almost identical to the list data type, except
in two ways. First, tuples are typed with parentheses, ( and ),
instead of square brackets, [ and ].
Tuples are immutable:
Tuples cannot have their values modified, appended, or removed.
Example:
eggs = ('hello', 42, 0.5)
eggs[1] = 99
print(eggs).
OUTPUT:
File "main.py", line 2, in <module>
Page 08 of 02
22PLC15B
eggs[1] = 99
TypeError: 'tuple' object does not support item assignment
Module-3
Q. 05 a Explain Python string handling methods with examples:
L2 10
split(),endswith(),
ljust(), center(), lstrip()
1. split()
The split() method is used to split a string into a list of substrings based on
a specified delimiter. For example:
m
words = text.split(" ")
print(words)
2. endswith()
co
The endswith() method is used to check if a string ends with a specified
suffix. It returns True if the string ends with the specified suffix, and False
otherwise. For example:
# Output: True
3. ljust()
dg
The ljust() method is used to left-justify a string within a specified width
by adding padding characters (usually spaces) to the right side of the
string. For example:
text = "Hello"
padded_text = text.ljust(10)
print(padded_text)
ue
4. center()
The center() method is used to center a string within a specified width by
adding padding characters (usually spaces) to both sides of the string. For
vt
example:
text = "Hello"
centered_text = text.center(10)
print(centered_text)
5. lstrip()
The lstrip() method is used to remove leading (leftmost) whitespace
characters (or other specified characters) from a string. For example:
Page 09 of 02
22PLC15B
# Output: 'Hello'
b Explain reading and saving python program variables using shelve module
L2 06
with suitable Python program.
m
In the Shelve Module, a shelf object is defined, which acts like a
dictionary-type object, and it is persistently stored in the disk file of our
computer.
co
Enter the following into the interactive shell:
import shelve
>>> shelfFile = shelve.open('mydata')
>>> cats = ['Zophie', 'Pooka', 'Simon']
>>> shelfFile['cats'] = cats
>>> shelfFile.close() e.
programs can use the shelve module to later reopen and retrieve the data
from these shelf files. Shelf values don’t have to be opened in read or write
mode they can do both once opened. Enter the following into the interactive
shell:
dg
>>> shelfFile = shelve.open('mydata')
>>> type(shelfFile)
<class 'shelve.DbfilenameShelf'>
>>> shelfFile['cats']
['Zophie', 'Pooka', 'Simon']
>>> shelfFile.close()
ue
c Develop a Python program to read and print the contents of a text file. L3 04
An example Python program that reads and prints the contents of a text file:
filename = "example.txt"
with open(filename, "r") as file:
contents = file.read()
vt
print(contents)
OR
Q. 06 a Explain Python string handling methods with examples: join(),
L2 10
startswith(),rjust(),strip(),rstrip()
1. join():
The join() method is useful when you have a list of strings that need to be
joined together into a single string value.
For example, enter the following into the interactive shell:
Page 010 of
02
22PLC15B
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
2. startswith()
The startswith() method is used to check if a string starts with a specific
substring. It takes a substring as input and returns a boolean value indicating
whether the string starts with the given substring or not.
3. rjust()
The rjust() method is used to right-justify a string by adding spaces to the left
of the string.
m
>>> 'Hello'.rjust(30)
‘ Hello’
4. strip()
The strip() method is used to remove any leading or trailing whitespace from a
co
string. It returns a new string with the whitespace removed.
>>> string = ' Hello World '
>>> print(string.strip())
Hello World
5. rstrip()
side.
result = text.rstrip()
dg
print(result)
# Output: ' Hello, World!'
b Explain with suitable Python program segments: (i) os.path.basename() (ii)
L2 05
os.path.join().
of the file path given as input. The base name is the last part of the
path, after the last occurrence of the path separator (‘/’ on Unix and
‘\’ on Windows) or drive separator (‘:’ on Windows). Here is an
example of how to use os.path.basename():
import os
file_path = '/home/user/documents/example.txt'
# Output:
example.txt
Page 011 of
02
22PLC15B
import os
# Example directory and file names
dir_name = 'documents'
file_name = 'example.txt'
m
# Output: /home/user/documents/example.txt
c Develop a Python program find the total size of all the files in the given L3 05
directory.
import os
co
# assign size
size = 0
# get size
e.
for ele in os.scandir(Folderpath):
size+=os.path.getsize(ele)
print(size)
dg
Output:
566434
ue
vt
Page 012 of
02
22PLC15B
Module-4
Q. 07 a Explain permanent delete and safe delete with a suitable Python
L2 08
programming example to each.
import os
m
# remove the file permanently
os.remove(file_name)
Safe delete, on the other hand, is a type of deletion that allows data to be
co
removed from a storage device, but with the possibility of recovery if needed.
This type of deletion involves a process of overwriting the data with new
information
import os
file_name = "example.txt"
e.
# specify the file to be deleted
# open the file in write mode and overwrite with new data
with open(file_name, "w") as file:
dg
file.write("This file has been deleted.")
working directory) into a ZIP File by using relevant modules and suitable
methods.
import os
from zipfile import ZipFile
from os import path
from shutil import make_archive
vt
Page 013 of
02
22PLC15B
In python, assert is keyword. This statement takes as input a boolean
condition, which when returns true doesn’t do anything and continues the
normal flow of execution, but if it is computed to be false, then it raises an
AssertionError along with the optional message provided.
Where:
assert:keyword
condition: The boolean condition returning true or false.
error_message : The optional argument to be printed in console in case
of AssertionError
m
# initializing number
a =4
b =0
co
print("The value of a / b is : ")
assert b !=0, "Zero Division Error"
print(a /b)
Output:
AssertionError: Zero Division Error
a
(ii) shutil.rmtree().
e.
OR
Explain the functions with examples: (i) shutil.copytree() (ii) shutil.move()
L3 06
dg
shutil is a Python module that provides a file operations, such as copying,
moving, and deleting files and directories.
1. In this below example, shutil.copytree() is used to copy the entire
directory tree from the source directory to the destination directory.
Example:
import shutil
ue
Example:
import shutil
import shutil
# delete a directory tree
shutil.rmtree('/path/to/directory')
Page 014 of
02
22PLC15B
b Develop a Python program to traverse the current directory by listing sub-
L2 06
folders and files.
import os
for foldername, subfolder, files in os.walk('/home/secabiet/test'):
print('current folder is'+foldername)
for subf in subfolder:
print('subfolder of :'+foldername+':'+subf)
for fname in files:
m
print('file inside of :'+foldername+':'+fname)
OUTPUT
current folder is/home/secabiet/test
subfolder of :/home/secabiet/test:test1
co
file inside of :/home/secabiet/test:a.py
current folder is/home/secabiet/test/test1
Example -
import logging
logging.debug('The debug message is displaying')
ue
Output:
Module-5
Q. 09 a Explain the methods init__ and __str__ with suitable code example to
L2 06
each.
def __str__(self):
return f"Name: {self.name}, Age: {self.age}"
p = Person("John", 25)
print(p)
m
# Output:
Name: John, Age: 25
b Explain the program development concept ‘prototype and patch’ with
L2 06
suitable example.
co
c 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 L3 08
e.
complex number.Develop a program to read N (N >=2) complex
numbers and to compute the addition of N complex numbers.
c1 = Complex()
c2 = Complex()
c3 = Complex()
print("Enter first complex number")
c1.initComplex()
print("First Complex Number: ", end="")
vt
c1.display()
print("Enter second complex number")
c2.initComplex()
print("Second Complex Number: ", end="")
c2.display()
print("Sum of two complex numbers is ", end="")
c3.sum(c1,c2)
c3.display()
OUTPUT:
Enter first complex number
Enter the Real Part: 4
Enter the Imaginary Part: 6
First Complex Number: 4+6i
Page 016 of
02
22PLC15B
Enter second complex number
Enter the Real Part: 4
Enter the Imaginary Part: 6
Second Complex Number: 4+6i
Sum of two complex numbers is 8+12i
OR
Q. 10 a Explain the following with syntax and suitable code snippet:
i) Class definition ii) instantiation iii) passing an instance (or objects) L2 10
as an argument iv) instances as return values.
m
of the class and a colon.
Syntax
class ClassName:
co
#statements
Emp= Employee()
e.
Example: Observe the following statements:
class Time:
hour=0
minute=0
vt
second=0
def print_time(t):
print('%.2d:%.2d:%.2d' % (t.hour, t.minute, t.second))
def add_time(t1, t2):
sum=Time()
sum.hour = t1.hour + t2.hour
sum.minute = t1.minute + t2.minute
sum.second = t1.second + t2.second
return sum
t1 = Time()
t1.hour = 9
t1.minute = 45
t1.second = 0
Page 017 of
02
22PLC15B
t2 = Time()
t2.hour = 1
t2.minute = 35
t2.second = 0
t3 = Time()
t3=Time.add_time(t1,t2)
Time.print_time(t3)
OUTPUT:
10:80:00
Functions which take mutable arguments (e.g. lists) and change them
m
during execution are called modifiers
Example:
class Time:
hour=0
co
minute=0
second=0
def print_time(self):
print('%.2d:%.2d:%.2d' % (self.hour, self.minute,
self.second))
def increment(self):
self.second += self.second
if self.second >= 60:
e.
self.second -= 60
dg
self.minute += 1
if self.minute >= 60:
self.minute -= 60
self.hour += 1
time = Time()
ue
time.hour = 9
time.minute = 62
time.second = 12
time.increment()
time.print_time()
OUTPUT:
vt
10:02:24
*Bloom’s Taxonomy Level: Indicate as L1, L2, L3, L4, etc. It is also desirable to indicate the COs and POs to be
attained by every bit of questions.
Page 018 of
02