OOPS & Python Programming (4351108) - Summer 2025 Solution

Solution guide for OOPS & Python Programming (4351108) Summer 2025 exam

Question 1(a) [3 marks]

What is the purpose of a for loop in Python? Write an example.

Answer: A for loop is used to iterate over a sequence (like list, tuple, string) or other iterable objects and execute a block of code for each item in the sequence.

Code Example:

Python
  • Iteration: Automatically repeats code for each item
  • Simplicity: Cleaner than using while loops with counters

Mnemonic: "For Each Item Do"

Question 1(b) [4 marks]

List out rules for defining variables in python and list out data types in python.

Answer:

Rules for defining variables:

RuleExampleInvalid Example
Must start with letter or underscorename = "John"1name = "John"
Can contain letters, numbers, underscoresuser_1 = "Alice"user-1 = "Alice"
Case-sensitiveage and Age are different
Cannot use reserved keywordscount = 5if = 5

Python Data Types:

Data TypeDescriptionExample
intInteger numbersx = 10
floatDecimal numbersy = 10.5
strText stringsname = "John"
boolBoolean valuesis_active = True
listOrdered, changeable collectionfruits = ["apple", "banana"]
tupleOrdered, unchangeable collectioncoordinates = (10, 20)
dictKey-value pairsperson = {"name": "John", "age": 30}
setUnordered collection of unique itemsnumbers = {1, 2, 3}
  • Variable rules: Make them descriptive and meaningful
  • Data types: Python automatically determines the type

Mnemonic: "SILB-DTS" (String, Integer, List, Boolean, Dictionary, Tuple, Set)

Question 1(c) [7 marks]

Create a program to print prime numbers between 1 to N.

Answer:

Python

Algorithm Diagram:

  • Time complexity: O(N√N) - Optimized with square root approach
  • Space complexity: O(1) - Only uses constant space

Mnemonic: "Divide To Decide Prime"

Question 1(c) OR [7 marks]

Explain working of break, continue and pass statement in Python with examples.

Answer:

StatementPurposeExample
breakTerminates the loop completelyStop loop when condition met
continueSkips current iteration, continues with nextSkip specific items
passNull operation, does nothingPlaceholder for future code

1. break statement:

Python

2. continue statement:

Python

3. pass statement:

Python

Flow Control Diagram:

  • break: Exits completely from the loop
  • continue: Jumps to the next iteration
  • pass: Does nothing, placeholder for future code

Mnemonic: "BCP - Break Completely, Continue Partially, Pass silently"

Question 2(a) [3 marks]

Create a program that asks the user for a year and prints out whether it is a leap year or not.

Answer:

Python

Decision Tree:

  • Rule 1: Divisible by 4, not by 100
  • Rule 2: Or divisible by 400

Mnemonic: "4 Yes, 100 No, 400 Yes"

Question 2(b) [4 marks]

What are the key differences between a list and a tuple in Python?

Answer:

FeatureListTuple
SyntaxCreated using []Created using ()
MutabilityMutable (can be changed)Immutable (cannot be changed)
MethodsMany methods (append, remove, etc.)Limited methods (count, index)
PerformanceSlowerFaster
Use CaseWhen modification neededWhen data shouldn't change
MemoryUses more memoryUses less memory

Comparison Diagram:

  • Lists: When you need to modify the collection
  • Tuples: When you need immutable data (faster, safer)

Mnemonic: "LIST - Lets Items Stay Transformable, TUPLE - Totally Unchangeable Permanent List Elements"

Question 2(c) [7 marks]

Create a program to find the sum of all the positive numbers entered by the user. As soon as the user enters a negative number, stop taking in any further input from the user and display the sum.

Answer:

Python

Process Flow:

  • Loop control: Terminates on negative input
  • Accumulator: Adds each positive number to running total

Mnemonic: "Sum Till Negative"

Question 2(a) OR [3 marks]

Create a program to find a maximum number among the given three numbers.

Answer:

Python

Comparison Logic:

  • Comparison: Uses logical operators to find maximum
  • Alternative: Built-in max() function for simplicity

Mnemonic: "Compare Each, Take Largest"

Question 2(b) OR [4 marks]

Given the str="abcdefghijklmnopqrstuvwxyz". Write a python program to extract every second character from above string.

Answer:

Python

String Slicing Diagram:

+---+---+---+---+---+---+---+---+---+---+---+
| a | b | c | d | e | f | g | h | i | j | k |...
+---+---+---+---+---+---+---+---+---+---+---+
  ^       ^       ^       ^       ^
  |       |       |       |       |
  0       2       4       6       8   (indices)
  • String slicing: [start:end:step] syntax
  • Step value: 2 selects every second character

Mnemonic: "Slice Step Selector"

Question 2(c) OR [7 marks]

Write a Python program to create a dictionary that stores student names and their marks. Display the names of students who have scored more than 75 marks.

Answer:

Python

Process Diagram:

  • Dictionary: Key-value pairs of student names and marks
  • Conditional filtering: Selects high scorers (>75)

Mnemonic: "Store All, Filter Some"

Question 3(a) [3 marks]

Write a program to find the length of a string excluding spaces.

Answer:

Python

String Processing:

"Hello World" → "HelloWorld" → Length: 10
  • Space removal: Using replace() or filtering
  • String length: Calculated after space removal

Mnemonic: "Count Characters, Skip Spaces"

Question 3(b) [4 marks]

List the dictionary methods in python and explain each with suitable examples.

Answer:

MethodDescriptionExample
clear()Removes all itemsdict.clear()
copy()Returns a shallow copynew_dict = dict.copy()
get()Returns value for keyvalue = dict.get('key', default)
items()Returns key-value pairsfor k, v in dict.items():
keys()Returns all keysfor k in dict.keys():
values()Returns all valuesfor v in dict.values():
pop()Removes item with keyvalue = dict.pop('key')
update()Updates dictionarydict.update({'key': value})

Code Example:

Python
  • Access methods: get(), keys(), values(), items()
  • Modification methods: update(), pop(), clear()

Mnemonic: "GCUP-KPIV" (Get-Copy-Update-Pop, Keys-Pop-Items-Values)

Question 3(c) [7 marks]

Explain Python's List data type in detail.

Answer:

Python List: An ordered, mutable collection that can store items of different data types.

FeatureDescriptionExample
CreationUsing square bracketsmy_list = [1, 'hello', True]
IndexingZero-based, negative indicesmy_list[0], my_list[-1]
SlicingExtract partsmy_list[1:3]
MutabilityCan be modifiedmy_list[0] = 10
MethodsMany built-in methodsappend(), insert(), remove()
NestingLists within listsnested = [[1, 2], [3, 4]]

Common List Methods:

MethodPurposeExample
append()Add item to endmy_list.append(5)
insert()Add at positionmy_list.insert(1, 'new')
remove()Remove by valuemy_list.remove('hello')
pop()Remove by indexmy_list.pop(2)
sort()Sort listmy_list.sort()
reverse()Reverse ordermy_list.reverse()

List Operations Diagram:

  • Versatility: Stores different data types in one collection
  • Dynamic sizing: Grows or shrinks as needed

Mnemonic: "CAMP-IS" (Create, Access, Modify, Process, Index, Slice)

Question 3(a) OR [3 marks]

Write a program to input a string from the user and print it in the reverse order without creating a new string.

Answer:

Python

String Reversing Visualization:

"Hello" → "olleH"

Indices:  0   1   2   3   4
String:   H   e   l   l   o
Reversed: o   l   l   e   H
Indices: -1  -2  -3  -4  -5
  • Slicing with negative step: Reverses without new string
  • Efficient: No extra memory used for new string

Mnemonic: "Slice Backwards"

Question 3(b) OR [4 marks]

List the dictionary operations in python and explain each with suitable examples.

Answer:

OperationDescriptionExample
CreationCreate a new dictionaryd = {'key': 'value'}
AccessAccess by keyvalue = d['key']
AssignmentAdd or update itemsd['new_key'] = 'new_value'
DeletionRemove itemsdel d['key']
MembershipCheck if key existsif 'key' in d:
LengthCount itemslen(d)
IterationLoop through itemsfor key in d:
ComprehensionCreate new dict{x: x**2 for x in range(5)}

Code Example:

Python
  • Key-based access: Fast lookup by keys
  • Dynamic structure: Add/remove items as needed

Mnemonic: "CADMIL" (Create, Access, Delete, Modify, Iterate, Length)

Question 3(c) OR [7 marks]

Explain Python's set data type in detail.

Answer:

Python Set: An unordered collection of unique, immutable items.

FeatureDescriptionExample
CreationUsing curly braces or set()my_set = {1, 2, 3} or set([1, 2, 3])
UniquenessNo duplicates allowed{1, 2, 2, 3} becomes {1, 2, 3}
UnorderedNo indexingCannot use my_set[0]
MutabilitySet itself is mutable, but elements must be immutableCan add/remove items
Math OperationsSet theory operationsunion, intersection, difference
Use CasesRemove duplicates, membership testingFast lookups

Common Set Operations:

OperationOperatorMethodDescription
Union|union()All elements from both sets
Intersection&intersection()Common elements
Difference-difference()Elements in first but not second
Symmetric Difference^symmetric_difference()Elements in either but not both

Set Operations Diagram:

  • Fast membership: O(1) average time complexity
  • Mathematical operations: Set theory operations built-in

Mnemonic: "SUMO" (Sets are Unique, Mutable, and Ordered-less)

Question 4(a) [3 marks]

Explain statistics module with any three methods.

Answer:

The statistics module provides functions for calculating mathematical statistics of numeric data.

MethodDescriptionExample
mean()Arithmetic averagestatistics.mean([1, 2, 3, 4, 5]) returns 3.0
median()Middle valuestatistics.median([1, 3, 5, 7, 9]) returns 5
mode()Most common valuestatistics.mode([1, 2, 2, 3, 4]) returns 2
stdev()Standard deviationstatistics.stdev([1, 2, 3, 4, 5]) returns 1.58...

Code Example:

Python
  • Data analysis: Functions for statistical calculations
  • Built-in module: No external installation needed

Mnemonic: "MMM Stats" (Mean, Median, Mode Statistics)

Question 4(b) [4 marks]

Explain function of user define function and user defined module in Python.

Answer:

FeatureUser-defined FunctionUser-defined Module
DefinitionBlock of reusable codePython file with functions/classes
PurposeCode organization and reuseOrganizing related code
CreationUsing def keywordCreating .py file
UsageCall by function nameImport using import statement
ScopeLocal to functionAccessible after import
BenefitsReduces redundancyPromotes code organization

User-defined Function Example:

Python

User-defined Module Example:

Python

Module Organization:

  • Function benefits: Code reuse, modular design
  • Module benefits: Organized code, namespace separation

Mnemonic: "FIR-MID" (Functions for Internal Reuse, Modules for Inter-file Distribution)

Question 4(c) [7 marks]

Write a Python code using user defined function to find the factorial of a given number using recursion.

Answer:

Python

Recursive Function Visualization:

  • Base case: Stops recursion when n=0 or n=1
  • Recursive case: Breaks problem into smaller subproblems

Mnemonic: "Factorial = Number times (Number minus one)!"

Question 4(a) OR [3 marks]

Explain math module with any three methods.

Answer:

The math module provides access to mathematical functions defined by the C standard.

MethodDescriptionExample
math.sqrt()Square rootmath.sqrt(16) returns 4.0
math.pow()Power functionmath.pow(2, 3) returns 8.0
math.floor()Round downmath.floor(4.7) returns 4
math.ceil()Round upmath.ceil(4.2) returns 5
math.sin()Sine functionmath.sin(math.pi/2) returns 1.0

Code Example:

Python
  • Mathematical operations: Advanced math functions
  • Constants: Mathematical constants like pi and e

Mnemonic: "SPT Math" (Square root, Power, Trigonometry in Math module)

Question 4(b) OR [4 marks]

Explain the concepts of global and local variables in Python.

Answer:

Variable TypeScopeDefinitionAccess
LocalInside functionDefined within functionOnly within the function
GlobalEntire programDefined outside functionsAnywhere in the program

Example:

Python

Variable Scope Diagram:

  • Global: Accessible everywhere but needs global keyword to modify
  • Local: Limited to function scope, freed after function execution

Mnemonic: "GLOBAL Goes Everywhere, LOCAL Lives in Functions"

Question 4(c) OR [7 marks]

Create code with user defined function to check if given string is palindrome or not.

Answer:

Python

Palindrome Testing Process:

  • String cleaning: Removes spaces, converts to lowercase
  • Comparison: Checks against reversed string
  • Example palindromes: "radar", "madam", "A man a plan a canal Panama"

Mnemonic: "Clean, Reverse, Compare"

Question 5(a) [3 marks]

Define class and object with example.

Answer:

Class: A blueprint for creating objects that defines attributes and methods.

Object: An instance of a class with specific attribute values.

Code Example:

Python

Class-Object Relationship:

  • Class: Template with attributes and methods
  • Object: Concrete instance with specific values

Mnemonic: "CAMBO" (Classes Are Molds, Build Objects)

Question 5(b) [4 marks]

Classify constructor. Explain any one in detail.

Answer:

Constructor TypeDescriptionWhen Used
Default constructorCreated by Python if none definedSimple class creation
Parameterized constructorTakes parameters to initializeCustomized object creation
Non-parameterized constructorTakes no parametersBasic initialization
Copy constructorCreates object from existing objectObject duplication

Parameterized Constructor Example:

Python

Constructor Flow:

  • Purpose: Initialize object attributes
  • Self parameter: Reference to the instance being created
  • Automatic call: Called when object is created

Mnemonic: "PICAN" (Parameters Initialize Constructor And Name)

Question 5(c) [7 marks]

Develop and explain a python code to implement hierarchical inheritance.

Answer:

Python

Hierarchical Inheritance Diagram:

  • Base class: Common attributes/methods for all vehicles
  • Derived classes: Specialized behaviors for specific vehicle types
  • Method inheritance: Child classes inherit parent class methods

Mnemonic: "Parents Share, Children Specialize"

Question 5(a) OR [3 marks]

What is the init method in Python? Explain its purpose with a suitable example.

Answer:

The __init__ method is a special method (constructor) in Python classes that is automatically called when an object is created.

Purpose:

  1. Initialize object attributes
  2. Set up the initial state of the object
  3. Execute code that must run when object is created

Example:

Python
  • Automatic execution: Called when object is created
  • Self parameter: References the current instance
  • Multiple parameters: Can accept any number of arguments

Mnemonic: "ASAP" (Attributes Set At Production)

Question 5(b) OR [4 marks]

Classify methods in Python class. Explain any one in detail.

Answer:

Method TypeDescriptionDefinition
Instance MethodOperates on object instanceRegular method with self
Class MethodOperates on class itselfDecorated with @classmethod
Static MethodDoesn't need class or instanceDecorated with @staticmethod
Magic/Dunder MethodSpecial built-in methodsSurrounded by double underscores

Instance Method Example:

Python

Method Classification:

  • Instance methods: Access and modify object state
  • Self parameter: Reference to the instance
  • Object-specific: Results depend on the instance state

Mnemonic: "SIAM" (Self Is Always Mentioned in instance methods)

Question 5(c) OR [7 marks]

Develop a Python code for Polymorphism and explain it.

Answer:

Python

Polymorphism Diagram:

  • Method overriding: Subclasses implement their own versions
  • Single interface: Same method name for different behavior
  • Flexibility: Code works with any class in the hierarchy
  • Dynamic binding: Correct method called based on object type

Mnemonic: "Same Method, Different Behavior"