OOPS & Python Programming (4351108) - Winter 2023 Solution
Solution guide for OOPS & Python Programming (4351108) Winter 2023 exam
Question 1(a) [3 marks]
List any 6 applications of Python programming language.
Answer:
Table of Python Applications:
| Application Area | Description |
|---|---|
| Web Development | Django, Flask frameworks |
| Data Science | Analysis and visualization |
| Machine Learning | AI model development |
| Desktop Applications | GUI using Tkinter, PyQt |
| Game Development | Pygame library |
| Automation | Scripting and testing |
Mnemonic: "Web Data Machine Desktop Game Auto"
Question 1(b) [4 marks]
List any 8 features of Python programming language.
Answer:
Table of Python Features:
| Feature | Description |
|---|---|
| Simple Syntax | Easy to read and write |
| Interpreted | No compilation needed |
| Object-Oriented | Supports OOP concepts |
| Dynamic Typing | Variables don't need type declaration |
| Cross-Platform | Runs on multiple OS |
| Large Libraries | Rich standard library |
| Open Source | Free to use and modify |
| Interactive | REPL environment |
Mnemonic: "Simple Interpreted Object Dynamic Cross Large Open Interactive"
Question 1(c) [7 marks]
Explain working of for and while loops in Python.
Answer:
For Loop:
- Iteration: Repeats over sequences (lists, strings, ranges)
- Syntax:
for variable in sequence: - Automatic: Handles iteration automatically
While Loop:
- Condition-based: Continues while condition is true
- Manual control: Programmer controls iteration
- Risk: Can create infinite loops if condition never becomes false
Diagram:
goat
Code Example:
Python
Mnemonic: "For Automatic, While Manual"
Question 1(c OR) [7 marks]
Explain working of break continue and pass statements in Python.
Answer:
Break Statement:
- Exit: Terminates the entire loop
- Usage: When specific condition is met
- Effect: Control moves to next statement after loop
Continue Statement:
- Skip: Skips current iteration only
- Usage: Skip specific values in iteration
- Effect: Moves to next iteration
Pass Statement:
- Placeholder: Does nothing, syntactic placeholder
- Usage: When syntax requires statement but no action needed
- Effect: No operation performed
Code Examples:
Python
Mnemonic: "Break Exits, Continue Skips, Pass Waits"
Question 2(a) [3 marks]
Develop a Python program to increment each element of list by one.
Answer:
Code:
Python
Mnemonic: "Loop Index or Comprehension"
Question 2(b) [4 marks]
Develop a Python program to read three numbers from the user and find the average of the numbers.
Answer:
Code:
Python
Key Points:
- Input: Use
float()for decimal numbers - Formula: Sum divided by count
- Output: Use f-string for formatting
Mnemonic: "Input Float, Sum Divide, Format Output"
Question 2(c) [7 marks]
Explain Python's list data type in detail.
Answer:
List Characteristics:
- Ordered: Elements maintain sequence
- Mutable: Can be modified after creation
- Heterogeneous: Can store different data types
- Indexed: Access elements using index (0-based)
List Operations Table:
| Operation | Syntax | Description |
|---|---|---|
| Creation | list = [1,2,3] | Create new list |
| Access | list[0] | Get element by index |
| Append | list.append(4) | Add element at end |
| Insert | list.insert(1,5) | Add at specific position |
| Remove | list.remove(2) | Remove first occurrence |
| Pop | list.pop() | Remove and return last |
| Slice | list[1:3] | Get sublist |
Code Example:
Python
Mnemonic: "Ordered Mutable Heterogeneous Indexed"
Question 2(a OR) [3 marks]
Develop a Python program to find sum of all elements in a list using for loop.
Answer:
Code:
Python
Mnemonic: "Initialize Zero, Loop Add, Print Total"
Question 2(b OR) [4 marks]
Develop a Python program to get input from user for principal, rate and no of years then calculate and display simple interest from that.
Answer:
Code:
Python
Formula:
- Simple Interest = (P × R × T) / 100
- Total Amount = Principal + Simple Interest
Mnemonic: "Principal Rate Time, Multiply Divide Hundred"
Question 2(c OR) [7 marks]
Explain Python's tuple data type in detail.
Answer:
Tuple Characteristics:
- Ordered: Elements maintain sequence
- Immutable: Cannot be modified after creation
- Heterogeneous: Can store different data types
- Indexed: Access using index (0-based)
Tuple Operations Table:
| Operation | Syntax | Description |
|---|---|---|
| Creation | tuple = (1,2,3) | Create new tuple |
| Access | tuple[0] | Get element by index |
| Count | tuple.count(2) | Count occurrences |
| Index | tuple.index(3) | Find first index |
| Slice | tuple[1:3] | Get sub-tuple |
| Length | len(tuple) | Get tuple size |
| Concatenate | tuple1 + tuple2 | Join tuples |
Code Example:
Python
Key Differences from List:
- Immutable: Cannot change elements
- Performance: Faster than lists
- Usage: For fixed data collections
Mnemonic: "Ordered Immutable Heterogeneous Indexed"
Question 3(a) [3 marks]
Explain any 3 random module methods.
Answer:
Random Module Methods Table:
| Method | Syntax | Description |
|---|---|---|
| random() | random.random() | Float between 0.0 to 1.0 |
| randint() | random.randint(1,10) | Integer between given range |
| choice() | random.choice(list) | Random element from sequence |
Code Example:
Python
Mnemonic: "Random Float, Randint Integer, Choice Select"
Question 3(b) [4 marks]
Develop a Python program that asks the user for a string and prints out the location of each 'a' in the string.
Answer:
Code:
Python
Key Points:
- Case-insensitive: Use
.lower()to find both 'a' and 'A' - Index tracking: Use range or enumerate
- Output format: Clear position indication
Mnemonic: "Loop Index Check Append Print"
Question 3(c) [7 marks]
Explain Python's string data type in detail.
Answer:
String Characteristics:
- Immutable: Cannot be changed after creation
- Sequence: Ordered collection of characters
- Indexed: Access characters using index
- Unicode: Supports all languages and symbols
String Methods Table:
| Method | Example | Description |
|---|---|---|
| upper() | "hello".upper() | Convert to uppercase |
| lower() | "HELLO".lower() | Convert to lowercase |
| strip() | " hello ".strip() | Remove whitespace |
| split() | "a,b,c".split(",") | Split into list |
| replace() | "hello".replace("l","x") | Replace substring |
| find() | "hello".find("e") | Find substring index |
| join() | ",".join(["a","b"]) | Join list elements |
String Operations:
Python
Key Features:
- Concatenation: Using + operator
- Repetition: Using * operator
- Membership: Using 'in' operator
- Formatting: f-strings, .format(), % formatting
Mnemonic: "Immutable Sequence Indexed Unicode"
Question 3(a OR) [3 marks]
Explain any 3 math module methods.
Answer:
Math Module Methods Table:
| Method | Syntax | Description |
|---|---|---|
| sqrt() | math.sqrt(16) | Square root calculation |
| pow() | math.pow(2,3) | Power calculation |
| ceil() | math.ceil(4.3) | Round up to integer |
Code Example:
Python
Mnemonic: "Square Root, Power Up, Ceiling Round"
Question 3(b OR) [4 marks]
Develop a Python program to get a string from the user and count total no. of Vowels present in that string.
Answer:
Code:
Python
Key Points:
- Vowel definition: Include both cases
- Loop through: Each character in string
- Count logic: Check membership and increment
Mnemonic: "Define Vowels, Loop Check, Count Increment"
Question 3(c OR) [7 marks]
Explain Python's set data type in detail.
Answer:
Set Characteristics:
- Unordered: No fixed sequence of elements
- Mutable: Can add/remove elements
- Unique: No duplicate elements allowed
- Iterable: Can loop through elements
Set Operations Table:
| Operation | Syntax | Description |
|---|---|---|
| Creation | set = {1,2,3} | Create new set |
| Add | set.add(4) | Add single element |
| Remove | set.remove(2) | Remove element (error if not found) |
| Discard | set.discard(2) | Remove element (no error) |
| Union | `set1 | set2` |
| Intersection | set1 & set2 | Common elements |
| Difference | set1 - set2 | Elements in set1 only |
Set Mathematical Operations:
Python
Key Uses:
- Remove duplicates: From lists
- Mathematical operations: Union, intersection
- Membership testing: Fast lookup
Mnemonic: "Unordered Mutable Unique Iterable"
Question 4(a) [3 marks]
What is the class in Python. How is it different from an object?
Answer:
Class vs Object Comparison:
| Aspect | Class | Object |
|---|---|---|
| Definition | Blueprint or template | Instance of class |
| Memory | No memory allocated | Memory allocated |
| Existence | Logical entity | Physical entity |
| Creation | Using class keyword | Using class constructor |
Example:
Python
Key Points:
- Class: Template defining properties and methods
- Object: Actual instance with specific values
- Relationship: One class, multiple objects
Mnemonic: "Class Blueprint, Object Instance"
Question 4(b) [4 marks]
Explain any four methods of dictionary data type of Python.
Answer:
Dictionary Methods Table:
| Method | Syntax | Description |
|---|---|---|
| keys() | dict.keys() | Get all keys |
| values() | dict.values() | Get all values |
| items() | dict.items() | Get key-value pairs |
| get() | dict.get('key') | Get value safely |
Code Example:
Python
Mnemonic: "Keys Values Items Get"
Question 4(c) [7 marks]
Develop a Python program that defines a user-defined module for performing some tasks. Import this module and use its functions.
Answer:
Module Creation (math_operations.py):
Python
Main Program (main.py):
Python
Key Points:
- Module creation: Separate .py file with functions
- Import methods: import module or from module import function
- Usage: Access using module.function() or direct function()
Mnemonic: "Create Import Use"
Question 4(a OR) [3 marks]
Define types of methods available in Python classes.
Answer:
Types of Methods Table:
| Method Type | Syntax | Description |
|---|---|---|
| Instance Method | def method(self): | Access instance variables |
| Class Method | @classmethod def method(cls): | Access class variables |
| Static Method | @staticmethod def method(): | Independent of class/instance |
Example:
Python
Mnemonic: "Instance Self, Class Cls, Static None"
Question 4(b OR) [4 marks]
Explain any four methods of string data type of Python.
Answer:
String Methods Table:
| Method | Syntax | Description |
|---|---|---|
| startswith() | str.startswith('pre') | Check if starts with substring |
| endswith() | str.endswith('suf') | Check if ends with substring |
| isdigit() | str.isdigit() | Check if all digits |
| count() | str.count('sub') | Count substring occurrences |
Code Example:
Python
Mnemonic: "Start End Digit Count"
Question 4(c OR) [7 marks]
Develop a Python program to find factorial of a number using recursive user defined function.
Answer:
Code:
Python
Recursion Flow:
goat
Key Points:
- Base case: Stops recursion (n=0 or n=1)
- Recursive case: Function calls itself
- Error handling: Check for negative input
Mnemonic: "Base Stop, Recursive Call, Error Check"
Question 5(a) [3 marks]
Develop a python program to Implement single inheritance.
Answer:
Code:
Python
Mnemonic: "Parent Child Inherit Override"
Question 5(b) [4 marks]
Explain the significance of constructors in Python classes.
Answer:
Constructor Significance:
| Aspect | Description |
|---|---|
| Initialization | Automatically called when object is created |
| Setup | Initialize instance variables with values |
| Memory | Allocate memory for object attributes |
| Validation | Validate input parameters during creation |
Constructor Types:
Python
Key Benefits:
- Automatic execution: No need to call manually
- Object state: Ensures proper initialization
- Code reusability: Common setup code in one place
Mnemonic: "Initialize Setup Memory Validate"
Question 5(c) [7 marks]
Develop a Python program to demonstrate method overriding using inheritance.
Answer:
Code:
Python
Method Overriding Diagram:
goat
Key Points:
- Same method name: In parent and child classes
- Different implementation: Child class provides specific logic
- Runtime decision: Correct method called based on object type
- Super() usage: Access parent class method
Mnemonic: "Same Name Different Logic Runtime Decision"
Question 5(a OR) [3 marks]
Explain concept of data encapsulation in Python.
Answer:
Data Encapsulation:
| Aspect | Description |
|---|---|
| Definition | Bundling data and methods together |
| Access Control | Restrict direct access to internal data |
| Data Hiding | Internal implementation hidden from outside |
| Interface | Provide controlled access through methods |
Implementation:
Python
Mnemonic: "Bundle Data Hide Interface"
Question 5(b OR) [4 marks]
Explain concept of abstract classes in Python.
Answer:
Abstract Classes:
| Concept | Description |
|---|---|
| Definition | Class that cannot be instantiated directly |
| Abstract Methods | Methods declared but not implemented |
| Implementation | Subclasses must implement abstract methods |
| Purpose | Define common interface for related classes |
Implementation using ABC:
Python
Key Features:
- Cannot instantiate: Abstract class cannot create objects
- Force implementation: Subclasses must implement abstract methods
- Common interface: Ensures consistent method signatures
Mnemonic: "Cannot Instantiate Force Implementation Common Interface"
Question 5(c OR) [7 marks]
Develop a python program to Implement multiple inheritance.
Answer:
Code:
Python
Multiple Inheritance Diagram:
goat
Key Points:
- Multiple parents: Child inherits from both Father and Mother
- Method Resolution Order (MRO): Determines which method is called
- Constructor calls: Explicitly call parent constructors
- Diamond problem: Python handles with MRO
Output:
Father constructor called
Mother constructor called
Child constructor called
Family Details:
Father: John
Mother: Mary
Child: Alice
Method Resolution:
Father works as Engineer
Mnemonic: "Multiple Parents MRO Constructor Diamond"