OOPS & Python Programming (4351108) - Summer 2024 Solution

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

Question 1(a) [3 marks]

Explain for loop working in Python.

Answer:

For loop repeats code block for each item in sequence like list, tuple, or string.

Syntax Table:

ComponentSyntaxExample
Basicfor variable in sequence:for i in [1,2,3]:
Rangefor i in range(n):for i in range(5):
Stringfor char in string:for c in "hello":

Diagram:

goat
  • Iteration: Loop variable gets each value from sequence one by one
  • Automatic: Python handles moving to next item automatically
  • Flexible: Works with lists, strings, tuples, ranges

Mnemonic: "For Each Item, Execute Block"


Question 1(b) [4 marks]

Explain working of if-elif-else in Python.

Answer:

Multi-way decision structure that checks multiple conditions in sequence.

Structure Table:

StatementPurposeSyntax
ifFirst conditionif condition1:
elifAlternative conditionselif condition2:
elseDefault caseelse:

Flow Diagram:

goat
  • Sequential: Checks conditions top to bottom
  • Exclusive: Only one block executes
  • Optional: elif and else are optional

Mnemonic: "If This, Else If That, Else Default"


Question 1(c) [7 marks]

Explain structure of a Python Program.

Answer:

Python program has organized structure with specific components in logical order.

Program Structure Table:

ComponentPurposeExample
CommentsDocumentation# This is comment
ImportExternal modulesimport math
ConstantsFixed valuesPI = 3.14
FunctionsReusable codedef function_name():
ClassesObjects blueprintclass ClassName:
Main codeProgram executionif __name__ == "__main__":

Program Architecture:

goat
  • Modular: Each section has specific purpose
  • Readable: Clear organization helps understanding
  • Maintainable: Easy to modify and debug
  • Standard: Follows Python conventions

Simple Example:

Python

Mnemonic: "Comment, Import, Constant, Function, Class, Main"


Question 1(c OR) [7 marks]

Explain features of Python Programming Language.

Answer:

Python has unique characteristics that make it popular for beginners and professionals.

Python Features Table:

FeatureDescriptionBenefit
SimpleEasy syntaxQuick learning
InterpretedNo compilationFast development
Object-OrientedClasses and objectsCode reusability
Open SourceFree to useNo licensing cost
Cross-PlatformRuns everywhereHigh portability

Feature Categories:

goat
  • Beginner-Friendly: Simple syntax like English language
  • Versatile: Used for web, AI, data science, automation
  • Rich Libraries: Huge collection of pre-built modules
  • Dynamic Typing: No need to declare variable types
  • Interactive: Can test code line by line in interpreter
  • High-Level: Handles memory management automatically

Code Example:

Python

Mnemonic: "Simple, Interpreted, Object-Oriented, Open, Cross-platform"


Question 2(a) [3 marks]

Explain any 3 operations done on Strings.

Answer:

String operations manipulate and process text data in various ways.

String Operations Table:

OperationMethodExampleResult
Concatenation+"Hello" + "World""HelloWorld"
Lengthlen()len("Python")6
Uppercase.upper()"hello".upper()"HELLO"

Operation Examples:

Python
  • Concatenation: Joins two or more strings together
  • Length: Counts total characters in string
  • Case Conversion: Changes letter cases (upper/lower)

Mnemonic: "Combine, Count, Convert"


Question 2(b) [4 marks]

Develop a Python program to convert temperature from Fahrenheit to Celsius unit using eq: C=(F-32)/1.8

Answer:

Program converts temperature using mathematical formula with user input.

Algorithm Table:

StepActionCode
1Get inputfahrenheit = float(input())
2Apply formulacelsius = (fahrenheit - 32) / 1.8
3Display resultprint(f"Celsius: {celsius}")

Complete Program:

Python

Test Cases:

  • Input: 32°F → Output: 0.00°C

  • Input: 100°F → Output: 37.78°C

  • User Input: Gets Fahrenheit temperature from user

  • Formula Application: Uses given conversion equation

  • Formatted Output: Shows result with decimal places

Mnemonic: "Input, Calculate, Output"


Question 2(c) [7 marks]

Explain in detail working of list data types in Python.

Answer:

List is ordered, mutable collection that stores multiple items in single variable.

List Characteristics Table:

PropertyDescriptionExample
OrderedItems have position[1, 2, 3]
MutableCan be changedlist[0] = 10
IndexedAccess by positionlist[0]
Mixed TypesDifferent data types[1, "hello", 3.14]

List Operations Diagram:

goat

Common List Methods:

MethodPurposeExample
append()Add item at endlist.append(5)
insert()Add at positionlist.insert(1, 15)
remove()Delete itemlist.remove(20)
pop()Remove last itemlist.pop()
len()Get lengthlen(list)

Example Code:

Python
  • Dynamic Size: Can grow or shrink during execution
  • Zero Indexing: First element at index 0
  • Slicing: Can extract portions using [start:end]
  • Nested Lists: Can contain other lists

Mnemonic: "Ordered, Mutable, Indexed, Mixed"


Question 2(a OR) [3 marks]

Explain String formatting in Python.

Answer:

String formatting creates formatted strings by inserting values into templates.

Formatting Methods Table:

MethodSyntaxExample
f-stringsf"text {variable}"f"Hello {name}"
format()"text {}".format(value)"Age: {}".format(25)
% operator"text %s" % value"Name: %s" % "John"

Example Usage:

Python
  • Placeholder: marks where values go
  • Dynamic: Values inserted at runtime
  • Readable: Makes code cleaner than concatenation

Mnemonic: "Format, Insert, Display"


Question 2(b OR) [4 marks]

Develop a Python program to identify whether the scanned number is even or odd and print an appropriate message.

Answer:

Program checks if number is divisible by 2 to determine even or odd.

Logic Table:

ConditionResultMessage
number % 2 == 0Even"Number is even"
number % 2 != 0Odd"Number is odd"

Complete Program:

Python

Test Cases:

  • Input: 4 → Output: "4 is even"

  • Input: 7 → Output: "7 is odd"

  • Modulo Operator: % gives remainder after division

  • Conditional Logic: if-else determines result

  • User Feedback: Clear message about result

Mnemonic: "Input, Check Remainder, Display Result"


Question 2(c OR) [7 marks]

Explain in detail working of Set data types in Python.

Answer:

Set is unordered collection of unique items with no duplicate values allowed.

Set Characteristics Table:

PropertyDescriptionExample
UnorderedNo fixed position{1, 3, 2}
UniqueNo duplicates{1, 2, 3}
MutableCan be modifiedset.add(4)
IterableCan loop throughfor item in set:

Set Operations Diagram:

goat

Set Methods Table:

MethodPurposeExample
add()Add single itemset.add(6)
update()Add multiple itemsset.update([7, 8])
remove()Delete itemset.remove(3)
union()Combine setsset1.union(set2)
intersection()Common itemsset1.intersection(set2)

Example Code:

Python
  • Automatic Deduplication: Removes duplicate values automatically
  • Fast Membership: Quick checking if item exists
  • Mathematical Operations: Union, intersection, difference
  • No Indexing: Cannot access items by position

Mnemonic: "Unique, Unordered, Mutable, Mathematical"


Question 3(a) [3 marks]

Explain working of any 3 methods of math module.

Answer:

Math module provides mathematical functions for complex calculations.

Math Methods Table:

MethodPurposeExampleResult
math.sqrt()Square rootmath.sqrt(16)4.0
math.pow()Power calculationmath.pow(2, 3)8.0
math.ceil()Round upmath.ceil(4.3)5

Usage Example:

Python
  • Precision: More accurate than basic operators
  • Import Required: Must import math module first
  • Return Values: Usually return float numbers

Mnemonic: "Square root, Power, Ceiling"


Question 3(b) [4 marks]

Develop a Python program to find sum of all elements in a list using for loop.

Answer:

Program iterates through list and accumulates sum of all elements.

Algorithm Table:

StepActionCode
1Initialize sumtotal = 0
2Loop through listfor element in list:
3Add to sumtotal += element
4Display resultprint(total)

Complete Program:

Python

Test Case:

  • Input: [1, 2, 3, 4, 5] → Output: 15

  • Accumulator: Variable stores running total

  • Iteration: Loop visits each element once

  • Addition: Adds each element to running sum

Mnemonic: "Initialize, Loop, Add, Display"


Question 3(c) [7 marks]

Develop a Python program to check if two lists are having similar length. If yes then merge them and create a dictionary from them.

Answer:

Program compares list lengths and creates dictionary if they match.

Logic Flow Table:

StepConditionAction
1Check lengthslen(list1) == len(list2)
2If equalMerge and create dictionary
3If not equalDisplay error message

Process Diagram:

goat

Complete Program:

Python

Expected Output:

Dictionary created: {'name': 'John', 'age': 25, 'city': 'Mumbai'}
  • Length Comparison: Ensures lists can be paired properly
  • zip() Function: Pairs elements from both lists
  • dict() Constructor: Creates dictionary from paired elements
  • Error Handling: Prevents incorrect pairing

Alternative Method:

Python

Mnemonic: "Check Length, Zip, Create Dictionary"


Question 3(a OR) [3 marks]

Explain working of any 3 methods of statistics module.

Answer:

Statistics module provides functions for statistical calculations on numeric data.

Statistics Methods Table:

MethodPurposeExampleResult
statistics.mean()Average valuemean([1,2,3,4,5])3.0
statistics.median()Middle valuemedian([1,2,3,4,5])3
statistics.mode()Most frequentmode([1,1,2,3])1

Usage Example:

Python
  • Data Analysis: Helps understand data patterns
  • Built-in Functions: No need to write complex formulas
  • Accurate Results: Handles edge cases properly

Mnemonic: "Mean, Median, Mode"


Question 3(c OR) [7 marks]

Develop a Python program to count the number of times a character appears in a given string using a dictionary.

Answer:

Program creates dictionary where keys are characters and values are their counts.

Character Counting Algorithm:

StepActionCode
1Initialize dictionarychar_count = {}
2Loop through stringfor char in string:
3Count occurrenceschar_count[char] = char_count.get(char, 0) + 1
4Display resultsprint(char_count)

Counting Process:

goat

Complete Program:

Python

Alternative Method (More Pythonic):

Python

Example Output:

Input: "hello"
Output: {'h': 1, 'e': 1, 'l': 2, 'o': 1}
  • Dictionary Keys: Each unique character becomes a key
  • Dictionary Values: Count of character occurrences
  • get() Method: Returns 0 if key doesn't exist, avoiding errors
  • Iteration: Processes each character in string once

Mnemonic: "Loop, Check, Count, Store"


Question 4(a) [3 marks]

Explain working of Python class and objects with example.

Answer:

Class is blueprint for creating objects. Objects are instances of classes.

Class-Object Relationship:

ConceptPurposeExample
ClassTemplate/Blueprintclass Car:
ObjectInstance of classmy_car = Car()
AttributesData in classself.color = "red"
MethodsFunctions in classdef start(self):

Class Structure:

goat

Example Code:

Python
  • Encapsulation: Groups related data and functions together
  • Reusability: One class can create multiple objects
  • Organization: Better code structure and maintenance

Mnemonic: "Class Blueprint, Object Instance"


Question 4(b) [4 marks]

Develop a Python program to print all odd numbers in a list.

Answer:

Program filters list elements and displays only odd numbers.

Odd Number Check Table:

Numbernumber % 2Result
11Odd
20Even
31Odd
40Even

Complete Program:

Python

Alternative Methods:

Python

Expected Output:

Odd numbers in the list:
1 3 5 7 9
  • Modulo Operation: % operator finds remainder
  • Condition Check: If remainder is not 0, number is odd
  • Loop Iteration: Checks each number in list

Mnemonic: "Loop, Check Remainder, Print Odd"


Question 4(c) [7 marks]

Explain working of user defined functions in Python.

Answer:

User-defined functions are custom functions created by programmers to perform specific tasks.

Function Components Table:

ComponentPurposeSyntax
def keywordFunction declarationdef function_name():
ParametersInput valuesdef func(param1, param2):
BodyFunction codeIndented statements
returnOutput valuereturn value

Function Structure:

goat

Types of Functions:

TypeDescriptionExample
No parametersTakes no inputdef greet():
With parametersTakes inputdef add(a, b):
Return valueGives outputreturn a + b
No returnPerforms actionprint("Hello")

Example Functions:

Python

Function Benefits:

  • Reusability: Write once, use multiple times
  • Modularity: Break complex problems into smaller parts
  • Maintainability: Easy to update and debug
  • Readability: Makes code more organized and understandable
  • Testing: Can test individual functions separately

Variable Scope:

  • Local Variables: Exist only inside function
  • Global Variables: Accessible throughout program
  • Parameters: Act as local variables

Mnemonic: "Define, Parameters, Body, Return"


Question 4(a OR) [3 marks]

Explain working constructors in Python.

Answer:

Constructor is special method that initializes objects when they are created.

Constructor Details Table:

AspectDescriptionSyntax
Method nameAlways __init__def __init__(self):
PurposeInitialize objectSet initial values
Automatic callCalled during object creationobj = Class()
ParametersCan accept argumentsdef __init__(self, param):

Constructor Example:

Python
  • Automatic Execution: Runs immediately when object is created
  • Initialization: Sets up object's initial state
  • self Parameter: Refers to current object being created

Mnemonic: "Initialize, Automatic, Self"


Question 4(b OR) [4 marks]

Develop a Python program to find smallest number in a list without using min function.

Answer:

Program manually compares all elements to find the smallest value.

Finding Minimum Algorithm:

StepActionCode
1Assume first is smallestsmallest = list[0]
2Compare with othersfor num in list[1:]:
3Update if smaller foundif num < smallest:
4Display resultprint(smallest)

Complete Program:

Python

Alternative Method:

Python

Expected Output:

Smallest number: 5
  • Comparison Logic: Compare each element with current smallest
  • Update Strategy: Replace smallest when smaller number found
  • Linear Search: Check all elements once

Mnemonic: "Assume, Compare, Update, Display"


Question 4(c OR) [7 marks]

Explain working of user defined Modules in Python.

Answer:

User-defined modules are custom Python files containing functions, classes, and variables that can be imported and used in other programs.

Module Components Table:

ComponentPurposeExample
FunctionsReusable code blocksdef calculate_area():
ClassesObject blueprintsclass Shape:
VariablesShared dataPI = 3.14159
ConstantsFixed valuesMAX_SIZE = 100

Module Creation Process:

goat

Example Module Creation:

File: math_operations.py

Python

Using the Module:

Import Methods Table:

MethodSyntaxUsage
Import entire moduleimport math_operationsmath_operations.calculate_circle_area(5)
Import specific functionfrom math_operations import calculate_circle_areacalculate_circle_area(5)
Import with aliasimport math_operations as math_opsmath_ops.PI
Import allfrom math_operations import *calculate_circle_area(5)

Main Program:

Python

Module Benefits:

  • Code Reusability: Write once, use in multiple programs
  • Organization: Keep related functions together
  • Namespace: Avoid naming conflicts
  • Maintainability: Easy to update and debug
  • Collaboration: Share modules with other developers

Module Search Path:

  1. Current directory
  2. PYTHONPATH environment variable
  3. Standard library directories
  4. Site-packages directory

Best Practices:

  • Use descriptive module names
  • Include docstrings for documentation
  • Keep related functionality together
  • Avoid circular imports

Mnemonic: "Create File, Define Functions, Import, Use"


Question 5(a) [3 marks]

Explain single inheritance in Python with example.

Answer:

Single inheritance is when one class inherits properties and methods from exactly one parent class.

Inheritance Structure Table:

ComponentRoleExample
Parent ClassBase/Super classclass Animal:
Child ClassDerived/Sub classclass Dog(Animal):
Inheritanceclass Child(Parent):class Dog(Animal):

Inheritance Diagram:

goat

Example Code:

Python
  • Code Reuse: Child class gets parent's functionality automatically
  • Extension: Child can add new methods and attributes
  • Is-a Relationship: Dog is-a Animal

Mnemonic: "One Parent, One Child"


Question 5(b) [4 marks]

Explain concept of abstraction in Python with its advantages.

Answer:

Abstraction hides complex implementation details and shows only essential features to the user.

Abstraction Concepts Table:

ConceptDescriptionExample
Abstract ClassCannot be instantiatedclass Shape(ABC):
Abstract MethodMust be implemented@abstractmethod
InterfaceDefines method structuredef area(self):

Abstraction Implementation:

Python

Advantages Table:

AdvantageDescriptionBenefit
SimplicityHide complex detailsEasier to use
SecurityHide internal implementationData protection
MaintainabilityChange implementation without affecting usersFlexible updates
Code OrganizationClear structureBetter design
  • Hide Complexity: Users don't need to know internal workings
  • Consistent Interface: All child classes follow same structure
  • Force Implementation: Abstract methods must be defined in child classes

Mnemonic: "Hide Details, Show Interface"


Question 5(c) [7 marks]

Develop a Python program to demonstrate working of multiple and multi-level inheritances.

Answer:

Program shows both inheritance types: multiple (multiple parents) and multi-level (chain of inheritance).

Inheritance Types Comparison:

TypeStructureExample
MultipleChild inherits from 2+ parentsclass C(A, B):
Multi-levelGrandparent → Parent → Childclass C(B): where class B(A):

Inheritance Hierarchy:

goat

Complete Program:

Python

Expected Output:

=== Multi-level Inheritance ===
Buddy can eat
Buddy breathes air
Buddy can bark

=== Multiple Inheritance ===
Method from Father class
Method from Mother class
Method from Child class

Child inherits from Father: True
Child inherits from Mother: True

Key Differences:

AspectMultipleMulti-level
Parents2 or more direct parentsSingle parent chain
Syntaxclass C(A, B):class C(B): where B(A):
InheritanceHorizontalVertical
ComplexityHigher (diamond problem)Lower

Method Resolution Order (MRO):

  • Multiple: Python follows left-to-right order
  • Multi-level: Goes up the inheritance chain

Mnemonic: "Multiple Parents, Multi-level Chain"


Question 5(a OR) [3 marks]

Explain working of 3 types of methods in Python.

Answer:

Python classes have three types of methods based on how they access class data.

Method Types Table:

Method TypeDecoratorFirst ParameterPurpose
Instance MethodNoneselfAccess instance data
Class Method@classmethodclsAccess class data
Static Method@staticmethodNoneUtility functions

Example Code:

Python
  • Instance Methods: Work with object-specific data using self
  • Class Methods: Work with class-wide data using cls
  • Static Methods: Independent utility functions

Mnemonic: "Instance Self, Class Cls, Static None"


Question 5(b OR) [4 marks]

Explain polymorphism through inheritance in Python.

Answer:

Polymorphism allows objects of different classes to be treated as objects of common base class, with each implementing methods differently.

Polymorphism Concept Table:

AspectDescriptionExample
Same InterfaceCommon method namesarea() method
Different ImplementationEach class has own versionRectangle vs Circle area
Runtime DecisionMethod chosen during executionDynamic binding

Polymorphism Example:

Python

Benefits:

  • Flexibility: Same code works with different object types
  • Extensibility: Easy to add new classes without changing existing code
  • Maintainability: Changes in one class don't affect others

Mnemonic: "Same Name, Different Behavior"


Question 5(c OR) [7 marks]

Develop a Python program to demonstrate working of hybrid inheritance.

Answer:

Hybrid inheritance combines multiple and multi-level inheritance in single program structure.

Hybrid Inheritance Structure:

goat

Inheritance Types in Hybrid:

LevelTypeClasses
1SingleAnimal → Mammal
2MultipleMammal → Dog, Cat
3MultipleDog, Cat → Pet

Complete Program:

Python

Expected Output:

=== Hybrid Inheritance Demo ===

--- Creating Hybrid Pet ---

--- Methods from Animal (Great-grandparent) ---
Buddy can eat
Buddy can sleep

--- Methods from Mammal (Grandparent) ---
Buddy breathes air
Buddy gives birth to babies

--- Methods from Dog (Parent 1) ---
Buddy barks: Woof!
Buddy is loyal to owner

--- Methods from Cat (Parent 2) ---
Buddy meows: Meow!
Buddy is independent

--- Own Methods ---
Buddy loves to play
Name: Buddy, Breed: Labrador-Persian Mix

--- Inheritance Chain ---
MRO (Method Resolution Order): (<class '__main__.HybridPet'>, <class '__main__.Dog'>, <class '__main__.Cat'>, <class '__main__.Mammal'>, <class '__main__.Animal'>, <class 'object'>)

Is HybridPet subclass of Animal? True
Is HybridPet subclass of Dog? True
Is HybridPet subclass of Cat? True

Key Features of Hybrid Inheritance:

  • Complex Structure: Combines different inheritance types
  • Method Resolution Order: Python follows specific order for method lookup
  • Diamond Problem: Handled automatically by Python's MRO
  • Flexibility: Access to methods from multiple parent classes

Advantages:

  • Rich Functionality: Inherits from multiple sources
  • Code Reuse: Maximum utilization of existing code
  • Relationship Modeling: Represents complex real-world relationships

Challenges:

  • Complexity: Harder to understand and maintain
  • Name Conflicts: Multiple parents may have same method names
  • Memory Usage: Objects carry more overhead

Mnemonic: "Hybrid Combines All Types"