Python Model Paper Solution
Python Model Paper Solution
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:
● Happens when Python converts a value to a larger or compatible data type to avoid data
loss.
Example:
a = 10 # int
b = 2.5 # float
print(c) # 12.5
● You use built-in functions like int(), float(), str(), list(), etc.
Example:
x = "123" # string
print(y) # 123
[Link] a Python program with a while loop to display the Fibonacci sequence up to n
terms entered by the user.
Answer:
a, b = 0, 1
count = 0
if n <= 0:
else:
print("Fibonacci sequence:")
b = next_term
count += 1
Output:
Fibonacci sequence:
0112358
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.
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.
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:
if i % 3 == 0 and i % 5 == 0:
# 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 …
Answer:
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
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
Syntax:
s t r i n g [ s t a r t : end : s t e p ]
# 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: ]
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:
Concatenation means joining two or more strings together. In Python, this is done using the +
operator.
Example:
f i r s t = " Hello"
Output:
H e l l o World
Explanation:
3. String Repetition
Example:
r e p e a t _msg = message * 3
Output:
Explanation:
Operator Meaning
== Equal to
!= Not equal
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:
● " 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:
Data type Can store different data types (int, Usually stores elements of t
flexibility float, string, etc.) data type
Given:
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:
p r i n t ( nums)
Output:
When you assign a list to another variable, both variables refer to the same memory location.
So, modifying one will affect the other.
l i s t 1 = [ 1, 2, 3]
l i s t 2 [ 0] = 99
print(list1)
print(list2)
Output:
[ 99, 2, 3]
[ 99, 2, 3]
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]
l i s t 2 [ 0] = 99
print(list1)
print(list2)
Output:
[ 1, 2, 3]
[ 99, 2, 3]
l i s t 1 = [ 1, 2, 3]
l i s t 2 = l i s t 1 . copy( )
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:
words = [Link]().split()
freq = {}
if cleaned_word:
freq[cleaned_word] = [Link](cleaned_word, 0) + 1
print(f"{word} : {count}")
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
print("Original array:")
print(arr)
print(mask)
filtered = arr[mask]
print(filtered)
Output:
[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:
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:
2. Mutable
4. Fast lookup
Program:
student_marks = {}
print("Insertion:")
student_marks["Alice"] = 85
student_marks["Bob"] = 78
student_marks["Charlie"] = 92
print(student_marks)
print("\nLookup:")
name = "Bob"
if name in student_marks:
else:
print("\nDeletion:")
print("Removed:", removed)
Output:
Insertion:
Lookup:
Bob's marks = 78
Deletion:
Removed: 92
Answer:
import numpy as np
print(matrix)
# Display shape
print([Link])
# Display transpose
print(matrix.T)
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
● Examples:
○ Images (.jpg)
○ Videos (.mp4)
○ Executables (.exe)
○ Serialized objects
3. Operations
Text Files
● Encoding/decoding is applied
Binary Files
● No newline handling
[Link]("Hello World\n")
[Link]("12345")
content = [Link]()
print(content)
data = [Link]()
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.
1. random Module:
The random module in Python is used to generate random numbers.
Functions commonly used are:
2. time Module:
The t i m e module provides functions to handle time-related operations.
Common functions:
i m p o r t random
import time
n = 5 # Number o f i n t e r v a l s
f o r i i n range( n) :
elapsed = end - s t a r t
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
I n t e r v a l 2 : W a i t i n g f o r 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
I n t e r v a l 4 : W a i t i n g f o r 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
Explanation:
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
def outer( ) :
def inner( ) :
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( )
Output:
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
c Differentiate between class attribute and instance attribute with suitable program
segments.
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:
# Creating objects
# Accessing a t t r i b u t e s
# Changing c l a s s a t t r i b u t e
# Changing i n s t a n c e a t t r i b u t e
Output:
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
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.
# 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
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 ( " 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) )
i m p o r t u t i l i t i e s as u
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) )
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
# 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
# b i n o m i a l . py
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
c .Explain the difference between ‘is’ and ‘==’ operators using immutable objects.
1. == Operator
2. i s Operator
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
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
● 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:
self.x = x
self.y = y
p1 = Point(3, 4)
p2 = p1 # aliasing
Output:
p1 is p2 → True
When we change:
p1.x = 100
Then printing p2. x also shows:
100
[Link] the need for exception handling in Python. Develop a program to illustrate: try,
except, else, and finally blocks.
Answer:
● Dividing by zero
2 except
3 else
4 finally
Example:
def divide_numbers():
try:
except ValueError:
except ZeroDivisionError:
print("Division successful!")
finally:
divide_numbers()
OUTPUT:
No Error
Enter numerator: 10
Enter denominator: 2
Division successful!
Result = 5.0
Error Occurs
Enter numerator: 10
Enter denominator: 0
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:
+ __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 )
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) :
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 ) :
# Creating objects
c1 = ComplexNumber( 3, 4)
c2 = ComplexNumber( 5, 6)
# Using o v e r l o a d e d +
c3 = c1 + c2
Output
F i r s t Complex Number: 3 + 4 i
Explanation
Program:
class Circle:
[Link] = radius
def area(self):
class Rectangle:
[Link] = length
[Link] = width
def area(self):
# Polymorphism in action
Output:
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.
1. Pure Functions
○ They may read the object’s attributes or other data but only compute and return
a result.
○ Example in OOP: a method that calculates interest but does not update the
balance.
2. Modifiers
○ 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.
class BankAccount:
self.account_number = account_number
[Link] = balance
if amount > 0:
[Link] += amount
else:
if amount <= 0:
else:
[Link] -= amount
def get_balance(self):
"""
return [Link]
"""
Pure function:
"""
return future_balance
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.
Aspect Description
Works with try and Runs after try and except blocks finish.
except
Example Program
try:
content = [Link]()
except FileNotFoundError:
finally:
print("Closing file...")
try:
[Link]()
except:
Closing file...
Closing file...