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:
| Rule | Example | Invalid Example |
|---|---|---|
| Must start with letter or underscore | name = "John" | 1name = "John" |
| Can contain letters, numbers, underscores | user_1 = "Alice" | user-1 = "Alice" |
| Case-sensitive | age and Age are different | |
| Cannot use reserved keywords | count = 5 | if = 5 |
Python Data Types:
| Data Type | Description | Example |
|---|---|---|
| int | Integer numbers | x = 10 |
| float | Decimal numbers | y = 10.5 |
| str | Text strings | name = "John" |
| bool | Boolean values | is_active = True |
| list | Ordered, changeable collection | fruits = ["apple", "banana"] |
| tuple | Ordered, unchangeable collection | coordinates = (10, 20) |
| dict | Key-value pairs | person = {"name": "John", "age": 30} |
| set | Unordered collection of unique items | numbers = {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:
| Statement | Purpose | Example |
|---|---|---|
| break | Terminates the loop completely | Stop loop when condition met |
| continue | Skips current iteration, continues with next | Skip specific items |
| pass | Null operation, does nothing | Placeholder 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:
| Feature | List | Tuple |
|---|---|---|
| Syntax | Created using [] | Created using () |
| Mutability | Mutable (can be changed) | Immutable (cannot be changed) |
| Methods | Many methods (append, remove, etc.) | Limited methods (count, index) |
| Performance | Slower | Faster |
| Use Case | When modification needed | When data shouldn't change |
| Memory | Uses more memory | Uses 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:
| Method | Description | Example |
|---|---|---|
clear() | Removes all items | dict.clear() |
copy() | Returns a shallow copy | new_dict = dict.copy() |
get() | Returns value for key | value = dict.get('key', default) |
items() | Returns key-value pairs | for k, v in dict.items(): |
keys() | Returns all keys | for k in dict.keys(): |
values() | Returns all values | for v in dict.values(): |
pop() | Removes item with key | value = dict.pop('key') |
update() | Updates dictionary | dict.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.
| Feature | Description | Example |
|---|---|---|
| Creation | Using square brackets | my_list = [1, 'hello', True] |
| Indexing | Zero-based, negative indices | my_list[0], my_list[-1] |
| Slicing | Extract parts | my_list[1:3] |
| Mutability | Can be modified | my_list[0] = 10 |
| Methods | Many built-in methods | append(), insert(), remove() |
| Nesting | Lists within lists | nested = [[1, 2], [3, 4]] |
Common List Methods:
| Method | Purpose | Example |
|---|---|---|
append() | Add item to end | my_list.append(5) |
insert() | Add at position | my_list.insert(1, 'new') |
remove() | Remove by value | my_list.remove('hello') |
pop() | Remove by index | my_list.pop(2) |
sort() | Sort list | my_list.sort() |
reverse() | Reverse order | my_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:
| Operation | Description | Example |
|---|---|---|
| Creation | Create a new dictionary | d = {'key': 'value'} |
| Access | Access by key | value = d['key'] |
| Assignment | Add or update items | d['new_key'] = 'new_value' |
| Deletion | Remove items | del d['key'] |
| Membership | Check if key exists | if 'key' in d: |
| Length | Count items | len(d) |
| Iteration | Loop through items | for key in d: |
| Comprehension | Create 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.
| Feature | Description | Example |
|---|---|---|
| Creation | Using curly braces or set() | my_set = {1, 2, 3} or set([1, 2, 3]) |
| Uniqueness | No duplicates allowed | {1, 2, 2, 3} becomes {1, 2, 3} |
| Unordered | No indexing | Cannot use my_set[0] |
| Mutability | Set itself is mutable, but elements must be immutable | Can add/remove items |
| Math Operations | Set theory operations | union, intersection, difference |
| Use Cases | Remove duplicates, membership testing | Fast lookups |
Common Set Operations:
| Operation | Operator | Method | Description |
|---|---|---|---|
| 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.
| Method | Description | Example |
|---|---|---|
mean() | Arithmetic average | statistics.mean([1, 2, 3, 4, 5]) returns 3.0 |
median() | Middle value | statistics.median([1, 3, 5, 7, 9]) returns 5 |
mode() | Most common value | statistics.mode([1, 2, 2, 3, 4]) returns 2 |
stdev() | Standard deviation | statistics.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:
| Feature | User-defined Function | User-defined Module |
|---|---|---|
| Definition | Block of reusable code | Python file with functions/classes |
| Purpose | Code organization and reuse | Organizing related code |
| Creation | Using def keyword | Creating .py file |
| Usage | Call by function name | Import using import statement |
| Scope | Local to function | Accessible after import |
| Benefits | Reduces redundancy | Promotes 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.
| Method | Description | Example |
|---|---|---|
math.sqrt() | Square root | math.sqrt(16) returns 4.0 |
math.pow() | Power function | math.pow(2, 3) returns 8.0 |
math.floor() | Round down | math.floor(4.7) returns 4 |
math.ceil() | Round up | math.ceil(4.2) returns 5 |
math.sin() | Sine function | math.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 Type | Scope | Definition | Access |
|---|---|---|---|
| Local | Inside function | Defined within function | Only within the function |
| Global | Entire program | Defined outside functions | Anywhere in the program |
Example:
Python
Variable Scope Diagram:
- Global: Accessible everywhere but needs
globalkeyword 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 Type | Description | When Used |
|---|---|---|
| Default constructor | Created by Python if none defined | Simple class creation |
| Parameterized constructor | Takes parameters to initialize | Customized object creation |
| Non-parameterized constructor | Takes no parameters | Basic initialization |
| Copy constructor | Creates object from existing object | Object 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:
- Initialize object attributes
- Set up the initial state of the object
- 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 Type | Description | Definition |
|---|---|---|
| Instance Method | Operates on object instance | Regular method with self |
| Class Method | Operates on class itself | Decorated with @classmethod |
| Static Method | Doesn't need class or instance | Decorated with @staticmethod |
| Magic/Dunder Method | Special built-in methods | Surrounded 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"