0% found this document useful (0 votes)
11 views49 pages

Python Model Paper Solution

The document is a model question paper for a Python Programming course for the B.E Degree Examination, covering various topics such as type conversion, loops, string operations, lists, dictionaries, and file handling. It includes questions requiring explanations, program development, and code examples. The paper is structured into modules with specific questions and programming tasks to assess students' understanding of Python concepts.

Uploaded by

shikaradhawan123
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)
11 views49 pages

Python Model Paper Solution

The document is a model question paper for a Python Programming course for the B.E Degree Examination, covering various topics such as type conversion, loops, string operations, lists, dictionaries, and file handling. It includes questions requiring explanations, program development, and code examples. The paper is structured into modules with specific questions and programming tasks to assess students' understanding of Python concepts.

Uploaded by

shikaradhawan123
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

Model Question Paper- I

First/ Second Semester B.E Degree Examination, 2025-26


PYTHON PROGRAMMING (1BPLC105B/205B)
TIME: 03 Hours Max. Marks:100

Answer any FIVE full questions, choosing at least ONE question from each.

Module - 1

[Link] the concept of type conversion in Python. Differentiate between implicit and
explicit conversion with examples.
Answer:

Type Conversion in Python

Type conversion means converting one data type into another.


For example: converting an integer to a float, a string to an integer, etc.

Python supports two types of conversions:

1. Implicit Type Conversion (Automatic)

● Performed automatically by Python.

● Happens when Python converts a value to a larger or compatible data type to avoid data
loss.

● You don’t need to write code to convert.

Example:

a = 10 # int

b = 2.5 # float

c=a+b # a (int) is automatically converted to float

print(c) # 12.5

print(type(c)) # <class 'float'>

Python converts 10 (int) to 10.0 (float) automatically.


2. Explicit Type Conversion (Type Casting)

● Performed manually by the programmer.

● You use built-in functions like int(), float(), str(), list(), etc.

● Needed when automatic conversion is not possible.

Example:

x = "123" # string

y = int(x) # convert string to int

print(y) # 123

print(type(y)) # <class 'int'>

[Link] a Python program with a while loop to display the Fibonacci sequence up to n
terms entered by the user.

Answer:

n = int(input("Enter the number of terms: "))

# First two terms of Fibonacci series

a, b = 0, 1

count = 0

if n <= 0:

print("Please enter a positive number.")

else:

print("Fibonacci sequence:")

while count < n:

print(a, end=" ")

next_term = a + b # Calculate next term


a=b # Move values forward

b = next_term

count += 1

Output:

Enter the number of terms: 7

Fibonacci sequence:

0112358

[Link] between a syntax error and a runtime error with examples.

Answer:

SYNTAX ERROR

Python can only execute a program if the program is syntactically correct; otherwise, the process
fails and returns an error message. Syntax refers to the structure of a program and the rules about
that structure.

If there is any syntax error, Python interpreter will throw SyntaxError.

Eg:-
RUNTIME ERROR

● The error does not appear until you run the program.

eg:-

[Link] the Collatz 3n + 1 sequence and explain how iteration and conditional
statements are used in its implementation.

Answer:

The condition for continuing with this loop is n != 1, so the loop will continue running until it
reaches its termination condition, (i.e. n == 1).

Each time through the loop, the program outputs the value of n and then checks whether it is
even or odd.

If it is even, the value of n is divided by 2 using integer division.

If it is odd, the value is replaced by n * 3 + 1.

Since n sometimes increases and sometimes decreases, there is no obvious proof that n will ever
reach 1, or that the program terminates. For some particular values of n, we can prove
termination. For example, if the starting value is a power of two, then the value of n will be even
each time through the loop until it reaches 1. The previous example ends with such a sequence,
starting with 16.

[Link] a program that prints all numbers from 1 to 100 that are divisible by 3 or 5 but
not both. Use continue or break statements wherever suitable.

Answer:

for i in range(1, 101):

# Check if divisible by both 3 and 5

if i % 3 == 0 and i % 5 == 0:

continue # Skip numbers divisible by BOTH

# Check if divisible by 3 OR 5

if i % 3 == 0 or i % 5 == 0:

print(i)

Output:

3 5 6 9 10 12 18 20 21 24 25 27 33 35 36 …

[Link] is meant by function composition? Illustrate with an example.

Answer:

Compose functions = use one function inside another.

If you have two functions f(x) and g(x), then

f(g(x)) is a composition — g(x) is executed first, and its result is passed to f(x).
Example:

def square(x):

return x * x

def add_five(x):

return x + 5

# Function composition: square(add_five(3))

result = square(add_five(3))

print("Result:", result)

Output:

Result: 64

Module – 2

Q.3.a. Explain the string operations in Python for slicing, concatenation, repetition, and
comparison with suitable examples.

Answer:

1. String Slicing

Slicing allows extracting a portion (substring) from a string using indexing.

Syntax:

s t r i n g [ s t a r t : end : s t e p ]

● start → index where the slice begins (included)

● end → index where the slice stops (excluded)

● step → how many characters to skip (default = 1)


Example:

t e x t = " Python Programming"

# E x t r a c t c h a r a c t e r s from i n d e x 0 t o 5

p a r t 1 = t e x t [ 0: 6]

# E x t r a c t c h a r a c t e r s from i n d e x 7 t o end

p a r t 2 = t e x t [ 7: ]

# Extract using negative index

l a s t _c h a r s = t e x t [ - 5: ]

# Using s t e p v a l u e

a l t e r n a t e _c h a r s = t e x t [ 0: 10: 2]

Output:

Python

Programming

mming

Pto

Explanation:

● t e x t [ 0: 6] → characters from index 0 to 5

● t e x t [ 7: ] → starts at index 7 and goes to the end

● t e x t [ - 5: ] → extracts the last 5 characters

● t e x t [ 0: 10: 2] → skips characters by 2 steps


2. String Concatenation

Concatenation means joining two or more strings together. In Python, this is done using the +
operator.

Example:

f i r s t = " Hello"

second = " World"

r e s u l t = f i r s t + " " + second

Output:

H e l l o World

Explanation:

● Strings are joined using +.

● " " is added to insert a space.

3. String Repetition

Repetition allows repeating a string multiple times using the * operator.

Example:

message = " H i ! "

r e p e a t _msg = message * 3

Output:

Hi! Hi! Hi!

Explanation:

● The string " H i ! " is repeated 3 times.


4. String Comparison

Strings can be compared using relational operators:

Operator Meaning

== Equal to

!= Not equal

< Less than (lexicographical)

> Greater than

<= Less than or equal

>= Greater than or equal

Python compares strings lexicographically (dictionary order) using ASCII/Unicode values.

Capital letters have smaller ASCII values than lowercase letters, so " Apple" <
" a p p l e " is True.

Example:

s1 = " Apple"

s2 = " Banana"

s3 = " a p p l e "
p r i n t ( s1 == " Apple" )

p r i n t ( s1 < s2)

p r i n t ( s2 > s3)

p r i n t ( s1 < s3)

Output:

True

True

False

True

Explanation:

● " Apple" == " Apple" → Both are identical → True

● " Apple" < " Banana" → A comes before B in dictionary → True

● " Banana" > " a p p l e " → Since uppercase letters have smaller ASCII values,
" Banana" is considered less than " a p p l e " → so comparison becomes False.

● " Apple" < " a p p l e " → ' A' has ASCII 65 and ' a' has ASCII 97, so True.

Q.3.b. Define a list. How is it different from an array? Develop a Python statement to
access the third element of a list: nums = [3, 6, 9, 12].

Definition of a List

A list in Python is an ordered collection of elements that can store multiple values in a single
variable. Lists are mutable, meaning their elements can be changed after creation. They can
contain elements of different data types such as integers, strings, floats, or even other lists.
Example of a list:

nums = [10, 20, "Hello", 5.5]


Difference Between a List and an Array

Feature List (Python) Array

Data type Can store different data types (int, Usually stores elements of t
flexibility float, string, etc.) data type

Memory usage Requires more memory More memory-efficient

Mutability Mutable Mutable

Usage Best for general-purpose Best for numerical and math


programming operations

Availability Built-in data structure in Python Requires additional module


a r r a y or NumPy) for use

Python Statement to Access the Third Element

Given:

nums = [3, 6, 9, 12]

To access the third element, use index 2 (since indexing starts at 0):

print(nums[2])

Output:

✔ So, the third element of the list nums is accessed using nums[ 2] .
Q.3.c. Develop a program to count the number of words in a given line of text.

Answer:

program:

line=input("Enter a sentence:")
word_count=0
for i in line:
if i==" ":
word_count+=1
print("The number of words in the line is:",word_count+1)

Output:
Enter a sentence:Hi how are you?
The number of words in the line is: 4

Q.4.a. Explain mutability in lists. Illustrate the difference between modifying a list and
creating a clone of it using examples.

Mutability in Lists

In Python, lists are mutable, meaning their elements can be changed, added, or removed after the
list is created.
This is different from immutable types (like strings or tuples), where values cannot be changed
once assigned.

Because lists are mutable, operations such as assigning a new value to a position, appending
elements, or deleting elements are allowed.

Example of Mutability:

nums = [ 10, 20, 30]

nums[ 1] = 50 # M o d i f y second element

p r i n t ( nums)

Output:

[ 10, 50, 30]


Here, the value 20 is replaced with 50, demonstrating mutability.

Modifying a List vs. Creating a Clone

When you assign a list to another variable, both variables refer to the same memory location.
So, modifying one will affect the other.

[Link] a List (Copy by Reference)

l i s t 1 = [ 1, 2, 3]

list2 = list1 # No new l i s t i s c r e a t e d

l i s t 2 [ 0] = 99

print(list1)

print(list2)

Output:

[ 99, 2, 3]

[ 99, 2, 3]

Both lists change because l i s t 1 and l i s t 2 refer to the same object.

2. Creating a Clone (Actual Copy)

To avoid modifying the original list, you must create a copy (clone).
There are multiple ways:

✔ Using slicing:

l i s t 1 = [ 1, 2, 3]

list2 = list1[ : ] # Creates a c l o n e

l i s t 2 [ 0] = 99

print(list1)

print(list2)
Output:

[ 1, 2, 3]

[ 99, 2, 3]

✔ Using the copy() method:

l i s t 1 = [ 1, 2, 3]

l i s t 2 = l i s t 1 . copy( )

Q.4.b. Develop a Python program to check if a string is a palindrome using slicing.

Answer:

Program:

string=input()
if string==string[::-1]:
print("The given string is a palindrome!")
else:
print("The given string is not a palindrome!")

Output:
Test Case 1:
madras
The given string is not a palindrome!
Test Case 2:
madam
The given string is a palindrome!

Q.4.c. Develop a program that takes a list of numbers and returns a new list containing
only the even numbers.

Answer:

Program:

num_list=[1,2,3,4,5,6,7,8,9]
even_list=[]
for i in num_list:
if i%2==0:
even_list.append(i)
print("The list containing only even numbers is:",even_list)
Output:
The list containing only even numbers is: [2, 4, 6, 8]

Module - 3

Q.5.a. Develop a Python program that counts the frequency of words in a paragraph using
a dictionary and displays the top three most frequent words.

Answer:

paragraph = input("Enter a paragraph:\n")

# Convert to lowercase and split into words

words = [Link]().split()

# Dictionary to store word frequencies

freq = {}

# Count word frequency

for word in words:

# Remove punctuation from each word

cleaned_word = "".join(ch for ch in word if [Link]())

if cleaned_word:

freq[cleaned_word] = [Link](cleaned_word, 0) + 1

# Sort dictionary by frequency in descending order

sorted_words = sorted([Link](), key=lambda x: x[1], reverse=True)

# Display top 3 most frequent words

print("\nTop 3 most frequent words:")


for word, count in sorted_words[:3]:

print(f"{word} : {count}")

[Link] is masking in NumPy? Develop a program to illustrate masking to filter array


elements.

Answer:

Masking in NumPy refers to selecting or filtering elements of an array using Boolean conditions.

A mask is simply a Boolean array (True/ F a l s e ) that has the same shape as the original array.

Where the mask is True, the element is selected; where it is F a l s e , the element is ignored.

Program:

import numpy as np

# Create a NumPy array

arr = [Link]([10, 45, 67, 89, 23, 50, 78, 5])

# Create a mask (condition)

mask = arr > 50

print("Original array:")

print(arr)

print("\nMask (True where element > 50):")

print(mask)

# Apply mask to filter elements

filtered = arr[mask]

print("\nFiltered elements (greater than 50):")

print(filtered)
Output:

[False False True True False False True False]

[67 89 78]

[Link] the use of the ‘with’ statement in file handling with a program.

Answer:

The with statement in Python is used in file handling to ensure that files are automatically
opened and closed properly.
It creates a context manager that takes care of closing the file even if errors occur inside the
block.

Program:

# Writing to a file using 'with'

with open("[Link]", "w") as file:

[Link]("Hello! This is a sample file.\n")

[Link]("With-statement makes file handling easier.")

# Reading from the same file using 'with'

with open("[Link]", "r") as file:

content = [Link]()

print("File Contents:")

print(content)

[Link] the key features and operations of Python dictionaries. How are they
different from lists? Develop suitable program to illustrate insertion, deletion, and lookup.

Answer:

A dictionary in Python is an unordered, mutable collection of key–value pairs.


1. Keys must be unique and immutable

○ Valid keys: string, number, tuple

○ Invalid keys: lists, sets

2. Mutable

○ You can add, update, or delete items.

3. Unordered (Python maintains insertion order from version 3.7+)

4. Fast lookup

○ Works like a hash table → O(1) average time for search.

Program:

# Creating an empty dictionary

student_marks = {}

# -------- INSERTION --------

print("Insertion:")

student_marks["Alice"] = 85

student_marks["Bob"] = 78

student_marks["Charlie"] = 92

print(student_marks)

# -------- LOOKUP --------

print("\nLookup:")

name = "Bob"
if name in student_marks:

print(f"{name}'s marks =", student_marks[name])

else:

print(f"{name} not found in dictionary.")

# -------- DELETION --------

print("\nDeletion:")

del student_marks["Alice"] # delete a key-value pair

print("After deleting Alice:", student_marks)

# Another safe deletion using pop()

removed = student_marks.pop("Charlie", "Not Found")

print("Removed:", removed)

print("Final dictionary:", student_marks)

Output:

Insertion:

{'Alice': 85, 'Bob': 78, 'Charlie': 92}

Lookup:

Bob's marks = 78

Deletion:

After deleting Alice: {'Bob': 78, 'Charlie': 92}

Removed: 92

Final dictionary: {'Bob': 78}


[Link] a NumPy program to: Create a 3×3 matrix of random integers. Display its
shape, transpose, and mean of all elements

Answer:

import numpy as np

# Create a 3×3 matrix of random integers (range 0–99)

matrix = [Link](0, 100, (3, 3))

print("3×3 Random Matrix:")

print(matrix)

# Display shape

print("\nShape of the matrix:")

print([Link])

# Display transpose

print("\nTranspose of the matrix:")

print(matrix.T)

print("\nMean of all elements:")

print([Link]())

[Link] how binary files differ from text files in terms of content and operations.
Illustrate with suitable program segments.

Answer:

1. Content Representation

Text Files
● Store data as human-readable characters (ASCII/Unicode)

Example content:

Hello

123

Binary Files

● Store data in raw byte format

● Not human readable

● Examples:

○ Images (.jpg)

○ Videos (.mp4)

○ Executables (.exe)

○ Serialized objects

2. File Mode Difference

Operation Text File Binary File Mode


Mode

Read "r" "rb"

Write "w" "wb"

Append "a" "ab"


Binary files use b → binary mode.

3. Operations

Text Files

● Data is read/written as strings

● Automatic handling of newline \n

● Encoding/decoding is applied

Binary Files

● Data is read/written as bytes objects (b'')

● No newline handling

● No encoding/decoding (raw bytes only)

Text File Example:

# Writing to a text file

with open("[Link]", "w") as f:

[Link]("Hello World\n")

[Link]("12345")

# Reading from a text file

with open("[Link]", "r") as f:

content = [Link]()

print("Text File Content:")

print(content)

Binary File example:

# Writing binary data (bytes)


with open("[Link]", "wb") as f:

[Link](b'\x41\x42\x43') # Writing bytes for A, B, C

# Reading binary data

with open("[Link]", "rb") as f:

data = [Link]()

print("Binary File Data:")

print(data) # Output: b'ABC'

Module - 4
Q7.a Explain the use of random and time modules in Python. Develop a program that
simulates a simple stopwatch that records random time intervals and calculates the average
elapsed time.

Use of random and time Modules in Python

1. random Module:
The random module in Python is used to generate random numbers.
Functions commonly used are:

● random( ) – generates a random float between 0 and 1


● u n i f o r m ( a, b) – generates a random float between a and b
● r a n d i n t ( a, b) – generates a random integer between a and b
This module is useful in simulations, games, testing, and generating unpredictable
values.

2. time Module:
The t i m e module provides functions to handle time-related operations.
Common functions:

● t i m e ( ) – returns the current time in seconds


● s l e e p ( seconds) – delays program execution
● Used for measuring elapsed time and creating time-based events
In stopwatch applications, it helps record start and end times.

Program: Simulating a Simple Stopwatch Using Random Time Intervals

i m p o r t random

import time

n = 5 # Number o f i n t e r v a l s

elapsed _t i m e s = [ ] # L i s t t o s t o r e each elapsed t i m e

p r i n t ( " Simple Stopwatch S i m u l a t i o n \ n" )

f o r i i n range( n) :

i n t e r v a l = random. u n i f o r m ( 1, 5) print( " Interval" ,


i +1, " : W a i t i n g f o r " , round( i n t e r v a l , 2) , " seconds" )

s t a r t = time. time( ) # Record s t a r t t i m e

time. sleep( i n t e r v a l ) # S i m u l a t e stopwatch d e l a y

end = t i m e . t i m e ( ) # Record end t i m e

elapsed = end - s t a r t

elapsed _t i m e s . append( elapsed )

p r i n t ( " Elapsed Time: " , round( elapsed , 2) , " seconds\ n" )


# C a l c u l a t e average t i m e

average = sum( elapsed _t i m e s ) / n

p r i n t ( " Average Elapsed Time: " , round( average, 2) , " seconds" )

Output:

Simple Stopwatch S i m u l a t i o n

I n t e r v a l 1 : W a i t i n g f o r 3. 27 seconds

Elapsed Time: 3. 27 seconds

I n t e r v a l 2 : W a i t i n g f o r 1. 94 seconds

Elapsed Time: 1. 94 seconds

I n t e r v a l 3 : W a i t i n g f o r 4. 58 seconds

Elapsed Time: 4. 58 seconds

I n t e r v a l 4 : W a i t i n g f o r 2. 31 seconds

Elapsed Time: 2. 31 seconds

I n t e r v a l 5 : W a i t i n g f o r 3. 89 seconds

Elapsed Time: 3. 89 seconds

Average Elapsed Time: 3. 20 seconds

Explanation:

● The program generates random time intervals using random. u n i f o r m ( ) .


● t i m e . s l e e p ( ) is used to pause the program, simulating a stopwatch.
● t i m e . t i m e ( ) records the start and end times.
● The elapsed time for each interval is stored and the average time is computed.

b .Explain the concept of namespaces in Python. Develop program to illustrate how


variable lookup follows the LEGB (Local, Enclosing, Global, Built-in) rule.

Concept of Namespaces in Python

A namespace in Python is a mapping of names (identifiers) to objects.


It ensures that variable names are unique and prevents naming conflicts.

Types of Namespaces

1. Local Namespace:
Contains names defined inside a function. Exists during function execution.

2. Enclosing Namespace:
Contains names in outer functions (in case of nested functions).

3. Global Namespace:
Contains names defined at the top level of a module or script.

4. Built-in Namespace:
Contains built-in functions and exceptions such as p r i n t ( ) , l e n ( ) , sum( ) , etc.

LEGB Rule

Python resolves variable names in the following order:

1. L – Local: Variables inside the current function.

2. E – Enclosing: Variables in outer/nested functions.


3. G – Global: Variables defined at the top level.

4. B – Built-in: Names in Python’s built-in module.

Program to Illustrate LEGB Rule

x = " G l o b a l X" # Global v a r i a b l e

def outer( ) :

x = " E n c l o s i n g X" # Enclosing v a r i a b l e

def inner( ) :

x = " L o c a l X" # Local v a r i a b l e

p r i n t ( " I n s i d e i n n e r ( ) : " , x)

inner( )

p r i n t ( " I n s i d e o u t e r ( ) : " , x)

outer( )

p r i n t ( " I n g l o b a l scope: " , x)

Output:

Inside inner ( ) : Local X

I n s i d e outer( ) : Enclosing X
I n g l o b a l scope: G l o b a l X

Explanation of Output

● Inside i n n e r ( ) → Python finds Local X in the local namespace.


● Inside o u t e r ( ) → No local in o u t e r ( ) , so it prints Enclosing X.
● In global scope → It uses Global X.
● Built-in scope is used only if no L, E, or G match are found.

c Differentiate between class attribute and instance attribute with suitable program
segments.

Difference Between Class Attribute and Instance Attribute

Class Attribute Instance Attribute

Belongs to the class and shared by all objects of Belongs to a specific object (instance).
the class.

Defined inside the class, but outside any Defined inside methods, usually inside
method. __i n i t _ _ ( ) .

Changing a class attribute affects all instances Changing an instance attribute affects only
(unless overridden). that instance.

Accessed using class name or object. Accessed only through the specific object.
Program to Illustrate Class and Instance Attributes

c l a s s Student:

course = " BTech" # Class a t t r i b u t e ( shared by a l l


objects)

d e f __i n i t _ _ ( s e l f , name, usn) :

s e l f . name = name # Instance a t t r i b u t e

s e l f . usn = usn # Instance a t t r i b u t e

# Creating objects

s1 = S t u d e n t ( " Ravi " , " 1RV22CS001" )

s2 = S t u d e n t ( " Anu" , " 1RV22CS002" )

# Accessing a t t r i b u t e s

p r i n t ( " S t u d e n t 1: " , s1. name, s1. usn, s1. course )

p r i n t ( " S t u d e n t 2: " , s2. name, s2. usn, s2. course )

# Changing c l a s s a t t r i b u t e

S t u d e n t . course = " B. E"

p r i n t ( " \ nAfter modifying class a t t r i b u t e : " )

p r i n t ( " S t u d e n t 1: " , s1. course )


p r i n t ( " S t u d e n t 2: " , s2. course )

# Changing i n s t a n c e a t t r i b u t e

s1. name = " Ravishankar "

p r i n t ( " \ nAfter modifying instance a t t r i b u t e : " )

p r i n t ( " S t u d e n t 1 name: " , s1. name)

p r i n t ( " S t u d e n t 2 name: " , s2. name)

Output:

S t u d e n t 1: Ravi 1RV22CS001 BTech

S t u d e n t 2: Anu 1RV22CS002 BTech

A f t e r modifying class a t t r i b u t e :

S t u d e n t 1: B. E

S t u d e n t 2: B. E

A f t e r modifying instance a t t r i b u t e :

S t u d e n t 1 name: Ravishankar

S t u d e n t 2 name: Anu

Explanation

● course is a class attribute, so both s1 and s2 share it.


● name and usn are instance attributes, so each object stores its own values.
● Updating class attribute updates it for all objects.
● Updating instance attribute updates it for that object only.

Q8 a. Develop python script to create a module [Link] with functions for square,cube,
and factorial of a number. Import it in another file using all three import variants.
Demonstrates the usage of each of the imported function.

Python Script to Create a Module and Import it Using All Methods

Step 1: Create a Module – u t i l i t i e s . py

# u t i l i t i e s . py

d e f square( n) :

return n * n

d e f cube( n) :

return n * n * n

d e f f a c t o r i a l ( n) :

fact = 1

f o r i i n range( 1, n+1) :

f a c t *= i

return fact

Step 2: Importing the Module in Another File

Create another file named [Link] to demonstrate all three import methods.
1. Import the entire module

import u t i l i t i e s

p r i n t ( " Square: " , u t i l i t i e s . square( 5) )

p r i n t ( " Cube: " , u t i l i t i e s . cube( 3) )

p r i n t ( " F a c t o r i a l : " , u t i l i t i e s . f a c t o r i a l ( 4) )

2. Import module with alias

i m p o r t u t i l i t i e s as u

p r i n t ( " Square: " , u. square( 6) )

p r i n t ( " Cube: " , u. cube( 2) )

p r i n t ( " F a c t o r i a l : " , u. f a c t o r i a l ( 5) )

3. Import specific functions

f rom u t i l i t i e s i m p o r t square, cube, f a c t o r i a l

p r i n t ( " Square: " , square( 4) )

p r i n t ( " Cube: " , cube( 7) )

p r i n t ( " F a c t o r i a l : " , f a c t o r i a l ( 6) )

Sample Output
Square: 25

Cube: 27

F a c t o r i a l : 24

Square: 36

Cube: 8

F a c t o r i a l : 120

Square: 16

Cube: 343

F a c t o r i a l : 720

Explanation

● A module [Link] is created with three functions: square( ) , cube( ) , and


factorial().

● In [Link], the module is imported in three ways:

1. i m p o r t u t i l i t i e s → Access using module name.

2. i m p o r t u t i l i t i e s as u → Access using alias.

3. from u t i l i t i e s i m p o r t square, cube, f a c t o r i a l → Direct


access without module name.

● Each imported version is used to demonstrate function calls.


b .Develop a custom module having function which calculates factorial of a [Link]
this custom module to a program to calculate binomial coefficient.

Custom Module for Factorial and Program for Binomial Coefficient

Step 1: Create a Custom Module – mymath. py

# mymath. py

d e f f a c t o r i a l ( n) :

fact = 1

f o r i i n range( 1, n+1) :

f a c t *= i

return fact

Step 2: Program to Import This Module and Calculate Binomial Coefficient

Create another file named [Link]:

# b i n o m i a l . py

i m p o r t mymath # i m p o r t i n g custom module

d e f b i n o m i a l _c o e f f i c i e n t ( n, r ) :

r e t u r n mymath. f a c t o r i a l ( n)

/ / ( mymath. f a c t o r i a l ( r ) * mymath. f a c t o r i a l ( n - r ) )
# Demonstration

n = 5

r = 2

p r i n t ( " B i n o m i a l C o e f f i c i e n t C( 5, 2) = " , b i n o m i a l _c o e f f i c i e n t ( n,
r))

Output:

B i n o m i a l C o e f f i c i e n t C( 5, 2) = 10

Explanation

● A custom module [Link] contains a function f a c t o r i a l ( ) that computes the


factorial of a number.
● The program [Link] imports this module using i m p o r t mymath.
● The f a c t o r i a l ( ) function is used three times to compute this.

c .Explain the difference between ‘is’ and ‘==’ operators using immutable objects.

Difference Between i s and == Operators (Using Immutable Objects)

1. == Operator

● Checks value equality.


● Returns True if the values of two objects are the same.
● Does not care whether the objects occupy the same memory location.

2. i s Operator

● Checks identity equality.


● Returns True only if both variables refer to the same object in memory.
● Used to compare object identity, not value.

Immutable Objects Example

Immutable objects in Python include:


i n t , f l o a t , s t r , tuple , bool.

Because they are immutable, Python may reuse memory locations for same values (object
interning).

Program to Illustrate == vs i s

# Using i n t e g e r s ( immutable o b j e c t s )

a = 1000

b = 1000

p r i n t ( a == b) # True → v a l u e s a r e e q u a l

p r i n t ( a i s b) # F a l s e → d i f f e r e n t memory l o c a t i o n s

# Using s m a l l i n t e g e r s ( i n t e r n e d by Python)

x = 10

y = 10

p r i n t ( x == y) # True

p r i n t ( x i s y) # True → same memory l o c a t i o n due t o i n t e r n i n g


# Using s t r i n g s ( immutable)

s1 = " h e l l o "

s2 = " h e l l o "

p r i n t ( s1 == s2) # True → v a l u e s a r e e q u a l

p r i n t ( s1 i s s2) # True → s t r i n g i n t e r n i n g

Sample Output

True

False

True

True

True

True

Explanation

● a and b have the same value, so a == b is True.

● But Python stores large integers separately, so a i s b is False.

● For small integers and short strings, Python interns them, so both x i s y and s1 i s
s2 are True.

Thus:

== → compares values
i s → compares memory identity

Module – 5

Q.9 [Link] a Python class Point with attributes x and y. Demonstrate sameness using ‘is’
operator, and show the effect of mutability when modifying one reference.

Answer:

class Point:

def __init__(self, x, y):

self.x = x

self.y = y

# Create one Point object

p1 = Point(3, 4)

# Make p2 refer to the SAME object

p2 = p1 # aliasing

# 1. Demonstrate sameness using 'is'

print("p1 is p2:", p1 is p2) # True → same object in memory

# 2. Show mutability: modifying one reference

p1.x = 100 # modify x using p1

print("p1.x =", p1.x) # 100

print("p2.x =", p2.x) # 100 → changed because p2 is the same object

Output:

p1 is p2 → True

When we change:

p1.x = 100
Then printing p2. x also shows:

100

p1 and p2 are aliases — two names for the same object.

Changing through one reference affects the other.

i s checks if two variables point to the same object.


Objects like class instances are mutable.
If p2 = p1, both refer to the same Point.
Changing p1 also changes p2.

[Link] the need for exception handling in Python. Develop a program to illustrate: try,
except, else, and finally blocks.

Answer:

In Python, errors can occur during program execution — such as:

● Dividing by zero

● Converting invalid input

● Accessing missing files

● Index out of range

If these errors are not handled, the entire program crashes.

Exception handling helps to:

1. Prevent program crashes

2. Control what happens when errors occur

3. Provide meaningful error messages

4. Allow recovery from unexpected situations

5. Execute important cleanup code (closing files, releasing resources)


[Link]

Contains code that may cause an error.

2 except

Catches and handles specific errors.

3 else

Runs only when no exception occurs.

4 finally

Runs always, even if an exception occurs.


Useful for closing files, releasing resources, or printing final messages.

Example:

def divide_numbers():

try:

# Code that may cause an exception

num1 = int(input("Enter numerator: "))

num2 = int(input("Enter denominator: "))

result = num1 / num2

except ValueError:

# Runs if input cannot be converted to integer

print("Error: Please enter only numbers.")

except ZeroDivisionError:

# Runs if denominator is zero

print("Error: Cannot divide by zero.")


else:

# Runs ONLY if no exception occurs in try block

print("Division successful!")

print("Result =", result)

finally:

# Runs ALWAYS, no matter what

print("Program execution completed.")

# call the function

divide_numbers()

OUTPUT:

No Error

Enter numerator: 10

Enter denominator: 2

Division successful!

Result = 5.0

Program execution completed.

Error Occurs

Enter numerator: 10

Enter denominator: 0

Error: Cannot divide by zero.

Program execution completed.

Q9. c. What is operator overloading? Illustrate with example using __add__().

Operator Overloading is a feature in Python that allows predefined operators (like +, - , * , <,
etc.) to work with user-defined objects in the same way they work with built-in data types.
In simple terms, it enables the operators to have different meanings based on the operands
used.

Python provides special methods (also called magic methods) such as:

Operator Magic Method

+ __add_ _ ( s e l f , o t h e r )

- __sub_ _ ( s e l f , o t h e r )

* __mul_ _ ( s e l f , o t h e r )

< __l t _ _ ( s e l f , o t h e r )

Example: Using __add_ _ ( ) for Operator Overloading

The following program demonstrates operator overloading using the + operator for adding two
complex numbers:

c l a s s ComplexNumber:

d e f __i n i t _ _ ( s e l f , r e a l , imag) :

self. real = real

s e l f . imag = imag

# Operator Overloading f o r +
d e f __add_ _ ( s e l f , o t h e r ) :

r e t u r n ComplexNumber( s e l f . r e a l + o t h e r . r e a l , s e l f . imag +
o t h e r . imag)

d e f __s t r _ _ ( s e l f ) :

r e t u r n f " { s e l f . r e a l } + { s e l f . imag} i "

# Creating objects

c1 = ComplexNumber( 3, 4)

c2 = ComplexNumber( 5, 6)

# Using o v e r l o a d e d +

c3 = c1 + c2

p r i n t ( " F i r s t Complex Number: " , c1)

p r i n t ( " Second Complex Number: " , c2)

p r i n t ( " R e s u l t o f A d d i t i o n : " , c3)

Output

F i r s t Complex Number: 3 + 4 i

Second Complex Number: 5 + 6 i

Result o f Addition: 8 + 10i

Explanation

● The operator + is used between two objects: c1 + c2.

Internally, Python calls:

c1. _ _ add_ _ ( c2)


● The __add_ _ ( ) method performs the addition of real and imaginary parts and returns a
new object.

● Thus, the operator + is overloaded to work with user-defined data types.

Q10. a. Develop a program to illustrate polymorphism by defining a common interface


method in two different classes.

Program:

class Circle:

def __init__(self, radius):

[Link] = radius

def area(self):

return 3.14 * [Link] * [Link]

class Rectangle:

def __init__(self, length, width):

[Link] = length

[Link] = width

def area(self):

return [Link] * [Link]

# Polymorphism in action

shapes = [Circle(5), Rectangle(4, 6)]

for shape in shapes:

print(f"The area is: {[Link]()}")

Output:

The area is: 78.5


The area is: 24

Q10.b. Outline the difference between pure functions and modifiers. Develop a program
code illustrating both using a class BankAccount.

Pure functions and modifiers are two different styles of methods you can write in a class.

Difference between Pure Functions and Modifiers

1. Pure Functions

○ Do not change the state (attributes) of any object.

○ They may read the object’s attributes or other data but only compute and return
a result.

○ Same inputs → same output (no hidden changes).

○ Example in OOP: a method that calculates interest but does not update the
balance.

2. Modifiers

○ Modify / update the state (attributes) of an object.

○ Often used for operations like deposit, withdraw, update profile, etc.

○ Their main purpose is the side effect (changing the object), not just returning a
value.

○ Example: a method that adds amount to balance (deposit) or subtracts it


(withdraw).

Program: BankAccount with Pure Function and Modifiers (Python)

class BankAccount:

def __init__(self, account_number, balance=0.0):

self.account_number = account_number
[Link] = balance

# ---------- MODIFIERS (change the object) ----------

def deposit(self, amount):

"""Modifier: adds amount to the account balance."""

if amount > 0:

[Link] += amount

print(f"Deposited {amount}. New balance = {[Link]}")

else:

print("Deposit amount must be positive.")

def withdraw(self, amount):

"""Modifier: subtracts amount from the account balance."""

if amount <= 0:

print("Withdrawal amount must be positive.")

elif amount > [Link]:

print("Insufficient funds. Withdrawal failed.")

else:

[Link] -= amount

print(f"Withdrew {amount}. New balance = {[Link]}")

# ---------- PURE FUNCTIONS (do NOT change the object) ----------

def get_balance(self):

"""

Pure function (in OOP sense):

returns current balance without modifying the object.


"""

return [Link]

def projected_balance(self, annual_rate, years):

"""

Pure function:

computes and returns the future balance with simple interest,

but DOES NOT update [Link].

"""

# Simple interest = P + P*r*t

future_balance = [Link] * (1 + annual_rate * years)

return future_balance

# ------------ Example usage ------------

# Create an account with initial balance

acct = BankAccount("SB1001", 1000.0)

print("Initial balance (using pure function):", acct.get_balance())

# Use pure function to calculate projected balance

proj = acct.projected_balance(annual_rate=0.05, years=2)

print("Projected balance after 2 years @5% (pure function):", proj)

print("Balance after projection (should be unchanged):", acct.get_balance())

# Use modifier functions to actually change the balance

[Link](500) # Modifier: changes [Link]

[Link](300) # Modifier: changes [Link]

print("Final balance (after modifiers):", acct.get_balance())


Q10.c. Explain the role of finally clause with an example.

The finally clause in exception handling is used to execute a block of code regardless of
whether an exception occurs or not.
It is mainly used for resource cleanup, such as closing files, releasing connections, or freeing
memory.

Role of finally Clause

Aspect Description

Execution guarantee finally always executes whether the exception is

Works with try and Runs after try and except blocks finish.
except

Common use cases Closing files, database connections, releasing res


stopping
processes.

Example Program

try:

file = open("[Link]", "r")

content = [Link]()

print("File content:", content)

except FileNotFoundError:

print("Error: File does not exist.")

finally:

print("Closing file...")

try:
[Link]()

print("File closed successfully.")

except:

print("File was not opened, so nothing to close.")

Output Scenario 1: File Exists

File content: Hello World!

Closing file...

File closed successfully.

Output Scenario 2: File Does Not Exist

Error: File does not exist.

Closing file...

File was not opened, so nothing to close.

You might also like