Model Question Paper- I
First/ Second Semester B.E Degree Examination, 2025-26
PYTHON PROGRAMMING (1BPLC105B/205B)
TIME: 03 Hours Max. Marks:100
Notes:
1. Answer any FIVE full questions, choosing at least ONE question from each MODULE
2. M: Marks, L: Bloom’s level, C: Course outcomes.
3.
Module - 1 M L C
Q.1 a Explain the concept of type conversion in Python. Differentiate 08 L2 CO1
between implicit and explicit conversion with examples.
Type Conversion
Type conversion is the process of converting one data type into
another data type.
Python supports automatic and manual type conversion.
1) Implicit Type Conversion
It is done automatically by Python.
No built-in function is used.
It happens when different data types are used in an expression.
Python converts lower data type into higher data type to avoid data
loss.
Example: When int and float are added, result becomes float.
2) Explicit Type Conversion
It is done manually by the programmer.
Built-in functions are used.
Common functions: int(), float(), str().
It gives more control over conversion.
Example: Converting string to integer using int() function.
Implicit Conversion Explicit Conversion
Automatic conversion Manual conversion
No function used Uses conversion functions
Done by compiler automatically Done by programmer
No data loss (generally) May cause data loss
Example: int → float Example: (int) 10.5
b Develop a Python program with a while loop to display the Fibonacci 08 L3 CO1
sequence up to n terms entered by the user.
n = int(input("Enter number of terms: "))
a=0
b=1
count = 0
while count < n:
print(a)
c=a+b
a=b
b=c
count = count + 1
1. Read the number of terms from the user.
2. Initialize first two numbers as 0 and 1.
3. Initialize counter variable count = 0.
4. Use while loop to repeat until count < n.
5. Print the current Fibonacci number.
6. Calculate next number by adding previous two numbers.
7. Update values of a and b.
8. Increment the counter in each iteration.
c Differentiate between a syntax error and a runtime error with 04 L2 CO1
examples.
Syntax Error Runtime Error
Occurs when Python rules are Occurs during execution of the
not followed program
Program does not execute Program starts but stops in
between
Detected before execution Detected during execution
Example: Missing colon or Example: Division by zero
bracket
OR
Q.2 a Describe the Collatz 3n + 1 sequence and explain how iteration and 08 L2 CO1
conditional statements are used in its implementation.
Program:
n = int(input("Enter a positive number: "))
while n != 1:
print(n)
if n % 2 == 0:
n = n // 2
else:
n=3*n+1
print(1)
Explanation:
1. Read a positive integer from the user.
2. Use a while loop that runs until n becomes 1.
3. Print the current value of n.
4. Use if-else statement for decision making:
o If n is even (n % 2 == 0), divide it by 2.
o If n is odd, multiply by 3 and add 1.
5. Repeat the process until n becomes 1.
6. Finally, print 1 as the last value in the sequence.
Output:
Enter a positive number: 6
6
3
10
5
16
8
4
2
1
b Develop a program that prints all numbers from 1 to 100 that are 08 L3 CO1
divisible by 3 or 5 but not both. Use continue or break statements
wherever suitable.
Program:
for i in range(1, 101):
if (i % 3 == 0 or i % 5 == 0) and not (i % 3 == 0 and i % 5 == 0):
print(i)
Explanation:
1. Use a for loop to iterate numbers from 1 to 100.
2. Check if the number is divisible by 3 using i % 3 == 0.
3. Check if the number is divisible by 5 using i % 5 == 0.
4. Use logical operators:
o or → divisible by 3 or 5.
o and not → ensure it is not divisible by both.
5. Print the numbers that satisfy the condition.
c What is meant by function composition? Illustrate with an example. 04 L2 CO1
Function composition means combining two or more functions.
The output of one function becomes the input of another function.
If f(x) and g(x) are two functions, then f(g(x)) is called function
composition.
It helps in writing modular and reusable programs.
Example:
If
f(x) = x + 2
g(x) = x × 3
Then
f(g(x)) = f(3x) = 3x + 2
Module – 2
Q.3 a Explain the string operations in Python for slicing, concatenation, 8 L2 CO2
repetition, and comparison with suitable examples.
1) Slicing
Slicing is used to extract a part of a string.
Syntax: string[start:end]
It returns characters from start index to end-1 index.
Example:
If s = "Python"
s[0:4] gives "Pyth"
2) Concatenation
Concatenation means joining two or more strings.
+ operator is used.
Example:
"Hello" + "World" gives "HelloWorld"
3) Repetition
Repetition means repeating a string multiple times.
* operator is used.
Example:
"Hi" * 3 gives "HiHiHi"
4) Comparison
Strings can be compared using comparison operators.
Operators: ==, !=, <, >
Comparison is based on ASCII values.
Example:
"apple" == "apple" → True
"abc" < "bcd" → True
b Define a list. How is it different from an array? Develop a Python 6 L3 CO2
statement to access the third element of a list: nums = [3, 6, 9, 12].
A list is a collection of elements enclosed in square brackets [ ].
It can store different types of data.
Lists are mutable.
Example:
nums = [3, 6, 9, 12]
Difference Between List and Array
List can store different data types.
Array stores same data type elements.
List is built-in in Python.
Array requires importing array module.
List size can change dynamically.
Access Third Element
Index starts from 0.
Third element index = 2
Statement:
nums[2]
c Develop a program to count the number of words in a given line of 6 L3 CO2
text.
text = input("Enter a line: ")
words = [Link]()
count = len(words)
print("Number of words:", count)
Read a line from user.
split() divides sentence into words.
len() counts number of words.
Print the result.
OR
Q.4 a Explain mutability in lists. Illustrate the difference between modifying 8 L2 CO2
a list and creating a clone of it using examples.
Mutability
Mutability means data can be changed after creation.
Lists are mutable in Python.
We can add, remove, or modify elements.
Example:
nums = [1, 2, 3]
nums[0] = 10
Now list becomes [10, 2, 3]
Modifying a List
Changes original list.
Example:
a = [1, 2, 3]
b=a
b[0] = 100
Both a and b become [100, 2, 3]
Creating a Clone of List
Creates a separate copy.
Original list does not change.
Example:
a = [1, 2, 3]
b = [Link]()
b[0] = 100
Now:
a = [1, 2, 3]
b = [100, 2, 3]
b Develop a Python program to check if a string is a palindrome using 6 L3 CO2
slicing.
text = input("Enter a string: ")
if text == text[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
Explanation
[::-1] reverses the string.
Compare original and reversed string.
If both are same → Palindrome.
c Develop a program that takes a list of numbers and returns a new list 6 L3 CO2
containing only the even numbers.
nums = [int(x) for x in input("Enter numbers: ").split()]
even_list = []
for n in nums:
if n % 2 == 0:
even_list.append(n)
print("Even numbers:", even_list)
Explanation
Read list of numbers.
Check each number using modulus operator.
If divisible by 2, add to new list.
Print even numbers list.
Module – 3
Q5 a Develop a Python program that counts the frequency of words in a 8 L3 CO2
paragraph using a dictionary and displays the top three most frequent
words.
text = input("Enter a paragraph: ")
words = [Link]()
freq = {}
for word in words:
word = [Link]()
if word in freq:
freq[word] += 1
else:
freq[word] = 1
sorted_words = sorted([Link](), key=lambda x: x[1], reverse=True)
print("Top three frequent words:")
for i in range(3):
print(sorted_words[i])
Explanation
Read paragraph from user.
Split paragraph into words.
Use dictionary to store word and its frequency.
Convert words to lowercase for accuracy.
Sort dictionary based on frequency in descending order.
Display top three words.
b What is masking in NumPy? Develop a program to illustrate masking 6 L3 CO3
to filter array elements.
Masking is used to filter elements of an array.
It selects elements based on a condition.
It returns only elements that satisfy the condition.
import numpy as np
arr = [Link]([10, 25, 30, 45, 50])
mask = arr > 30
filtered = arr[mask]
print("Original array:", arr)
print("Mask:", mask)
print("Filtered elements:", filtered)
Explanation
Create NumPy array.
Apply condition (arr > 30).
Boolean mask is created.
Only elements greater than 30 are selected.
c Explain the use of the ‘with’ statement in file handling with a 6 L2 CO4
program.
The with statement is used to open files.
It automatically closes the file after use.
It avoids manual closing using close() method.
It improves safety and readability.
Program
with open("[Link]", "w") as f:
[Link]("Hello Python")
with open("[Link]", "r") as f:
content = [Link]()
print(content)
Advantages
File closes automatically.
Prevents file corruption.
Cleaner and safer code.
OR
a Explain the key features and operations of Python dictionaries. How 8 L3 CO2
are they different from lists? Develop suitable program to illustrate
insertion, deletion, and lookup.
Dictionary stores data in key-value pairs.
Written inside { }.
Keys must be unique.
Values can be any data type.
Dictionaries are mutable.
Example:
student = {"name": "Ram", "age": 20}
Difference Between Dictionary and List
Dictionary stores key-value pairs.
List stores ordered elements.
Dictionary accessed using keys.
List accessed using index.
Dictionary uses { }.
List uses [ ].
Program for Insertion, Deletion and Lookup
student = {}
# Insertion
student["name"] = "Ram"
student["age"] = 20
# Lookup
print(student["name"])
# Deletion
del student["age"]
print(student)
b Develop a NumPy program to: 6 L3 CO3
Create a 3×3 matrix of random integers.
Display its shape, transpose, and mean of all elements.
import numpy as np
# Create 3x3 random integer matrix
matrix = [Link](1, 50, (3,3))
print("Matrix:\n", matrix)
# Display shape of matrix
print("Shape:", [Link])
# Display transpose of matrix
print("Transpose:\n", matrix.T)
# Display mean of all elements
print("Mean:", [Link]())
Explanation:
1. Import NumPy library using import numpy as np.
2. Create a 3×3 random integer matrix using [Link](1,
50, (3,3)).
3. .shape returns the dimensions (rows, columns) of the matrix.
4. .T gives the transpose of the matrix (rows become columns).
5. .mean() calculates the average of all elements in the matrix.
6. The results are printed using print() function.
c Explain how binary files differ from text files in terms of content and 6 L2 CO4
operations. Illustrate with suitable program segments.
Text Files
Stores data in readable form.
Stores characters.
Example: .txt files.
Uses modes like "r", "w".
Example:
with open("[Link]", "w") as f:
[Link]("Hello")
Binary Files
Stores data in binary format (0 and 1).
Not human readable.
Used for images, audio, etc.
Uses modes like "rb", "wb".
Example:
with open("[Link]", "wb") as f:
[Link](b"Hello")
Text File / Text Mode Binary File / Binary Mode
Text file → Readable format Binary file → Not readable format
Stores data as characters Stores data as bytes
Text mode → "r", "w" Binary mode → "rb", "wb"
Used for .txt, .csv files Used for images, audio, video files
Module – 4
Q.7 a Explain the use of random and time modules in Python. Develop a 8 L3 CO3
program that simulates a simple stopwatch that records random time
intervals and calculates the average elapsed time.
The random module is used to generate random numbers.
It is imported using import random.
randint(a, b) generates random integer between a and b.
It is used in games and simulations.
The time module is used to measure and control time.
It is imported using import time.
time() gives current time in seconds.
sleep(seconds) pauses the program for given seconds.
Program:
import random
import time
intervals = []
for i in range(5):
start = [Link]()
delay = [Link](1, 3)
[Link](delay)
end = [Link]()
[Link](end - start)
average = sum(intervals) / len(intervals)
print("Intervals:", intervals)
print("Average time:", average)
b Explain the concept of namespaces in Python. Develop program to 8 L3 CO3
illustrate how variable lookup follows the LEGB (Local, Enclosing,
Global, Built-in) rule.
Namespace is a container that stores variable names and their
values.
It avoids name conflicts in program.
Each function and module has its own namespace.
Python follows LEGB rule to search variables:
L – Local namespace (inside current function)
E – Enclosing namespace (inside outer function)
G – Global namespace (defined outside functions)
B – Built-in namespace (predefined names)
Python searches variables in this order: Local → Enclosing →
Global → Built-in.
Program:
x = "Global"
def outer():
x = "Enclosing"
def inner():
x = "Local"
print(x)
inner()
outer()
Output is Local because Python checks local namespace first.
c Differentiate between class attribute and instance attribute with 4 L2 CO5
suitable program segments.
Class attribute is defined inside the class.
It is shared by all objects of the class.
Same value for every object.
Instance attribute is defined inside constructor using self.
It is different for each object.
Each object has its own copy.
Program:
class Student:
college = "ABC College"
def init (self, name):
[Link] = name
s1 = Student("Ram")
s2 = Student("Shyam")
print([Link])
print([Link])
college is class attribute.
name is instance attribute.
OR
Q.8 a Develop python script to create a module [Link] with functions 8 L3 CO3
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.
A module is a file containing Python functions.
It helps in code reusability and organization.
[Link]
def square(n):
return n*n
def cube(n):
return n*n*n
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
Import using three variants:
1. Import whole module
import utilities
print([Link](4))
2. Import specific functions
from utilities import square, cube
print(square(3))
3. Import all functions
from utilities import *
print(factorial(5))
b Develop a custom module having function which calculates factorial 8 L3 CO3
of a number. Import this custom module to a program to calculate
binomial coefficient.
Create a module that calculates factorial.
Import it to compute binomial coefficient.
Formula: nCr = n! / (r! * (n-r)!)
factorial_module.py
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
Main program:
import factorial_module
n=5
r=2
result = factorial_module.factorial(n) / (
factorial_module.factorial(r) *
factorial_module.factorial(n-r))
print("Binomial Coefficient:", result)
c Explain the difference between ‘is’ and ‘==’ operators using 4 L2 CO5
immutable objects.
Difference Between ‘is’ and ‘==’ (4 Marks)
== compares values of two objects.
It returns True if values are equal.
is compares memory location of two objects.
It returns True if both refer to same object.
Example:
a = 10
b = 10
print(a == b)
print(a is b)
== checks value equality.
is checks object identity.
Module – 5
Q.9 a Create a Python class Point with attributes x and y. Demonstrate 8 L3 CO5
sameness using ‘is’ operator, and show the effect of mutability when
modifying one reference.
A class is a blueprint to create objects.
Attributes store data inside an object.
The is operator checks whether two references point to same
object.
Objects are mutable if their data can be changed.
Program:
class Point:
def init (self, x, y):
self.x = x
self.y = y
p1 = Point(2, 3)
p2 = p1
print(p1 is p2)
p2.x = 10
print(p1.x)
print(p2.x)
p1 is p2 returns True because both refer to same object.
Changing p2.x also changes p1.x due to mutability.
Both references point to same memory location.
b Explain the need for exception handling in Python. Develop a program 8 L3 CO5
to illustrate: try, except, else, and finally blocks.
Exception handling prevents program from crashing.
It handles runtime errors.
try block contains risky code.
except handles the error.
else runs if no error occurs.
finally always executes.
Program:
try:
a = int(input("Enter a number: "))
b = int(input("Enter another number: "))
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")
else:
print("Result is:", result)
finally:
print("Program finished")
If error occurs, except block runs.
If no error, else block runs.
Finally block runs in all cases.
c What is operator overloading? Illustrate with example using 4 L2 CO5
add ().
Operator overloading means giving special meaning to operators.
In Python, it is done using special methods.
add () is used to overload + operator.
Program:
class Number:
def init (self, value):
[Link] = value
def add (self, other):
return Number([Link] + [Link])
n1 = Number(5)
n2 = Number(10)
n3 = n1 + n2
print([Link])
Here + operator adds values of two objects.
It uses add () method.
OR
Q.10 a Develop a program to illustrate polymorphism by defining a common 8 L3 CO5
interface method in two different classes.
Polymorphism means same method name behaves differently.
Different classes can have same method name.
Program:
class Dog:
def speak(self):
print("Dog barks")
class Cat:
def speak(self):
print("Cat meows")
def make_sound(animal):
[Link]()
d = Dog()
c = Cat()
make_sound(d)
make_sound(c)
Both classes have speak() method.
Same interface but different behavior.
b Outline the difference between pure functions and modifiers. Develop 8 L3 CO5
a program code illustrating both using a class BankAccount.
Pure function does not modify original object.
It returns new value.
Modifier function changes object state.
Program:
class BankAccount:
def init (self, balance):
[Link] = balance
def get_balance(self):
return [Link]
def deposit(self, amount):
[Link] += amount
acc = BankAccount(1000)
print(acc.get_balance())
[Link](500)
print(acc.get_balance())
get_balance() is pure function.
deposit() is modifier because it changes balance.
c Explain the role of finally clause with an example. 4 L2 CO5
Finally block always executes.
It runs whether exception occurs or not.
Used to release resources like files.
Example:
try:
f = open("[Link]", "r")
print([Link]())
except FileNotFoundError:
print("File not found")
finally:
print("Execution completed")
Finally block ensures important code runs at the end.