Skip to main content
  1. Resources/
  2. Study Materials/
  3. Electronics & Communication Engineering/
  4. ECE Semester 5/

OOPS & Python Programming (4351108) - Summer 2024 Solution

31 mins· ·
Study-Material Solutions Python Oops 4351108 2024 Summer
Milav Dabgar
Author
Milav Dabgar
Experienced lecturer in the electrical and electronic manufacturing industry. Skilled in Embedded Systems, Image Processing, Data Science, MATLAB, Python, STM32. Strong education professional with a Master’s degree in Communication Systems Engineering from L.D. College of Engineering - Ahmedabad.
Table of Contents

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:

StartEMIBxotaeveccemkusYttetCeolsoheelnfEcoetxkox?eptciufbitoteide-tymNleoom-os-p-l-beC>ofhdteEycnikdnisfeqiuteenmcseleft
  • 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:

EiCxfheeTcbEScrulntkutodaeecri/kEebtfxlleioEcFCcfcnoahcTukdnleortdscnueiekdeti/ietoliCoEenioFhrxlfnaeesElcecenskludestbneeleoxctkelif
  • 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:

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

Simple Example:

# Program to calculate area
import math

PI = 3.14159

def calculate_area(radius):
    return PI * radius * radius

# Main execution
radius = float(input("Enter radius: "))
area = calculate_area(radius)
print(f"Area = {area}")

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:

LF---aenaSRDgtieyuumanarpdagelamesebilcPeytTF---heeocaIPEnhtnoxnutrtFireteeceranaaspbstlrliueebrtleCFeesoedmamt---uunrOLAiepactsertyngievSeoLuiSrbucrpeaproyrt
  • 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:

# Simple Python syntax
name = "Python"
print(f"Hello, {name}!")

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:

text = "Python"
# 1. Concatenation
result1 = text + " Programming"
# 2. Find length
result2 = len(text)
# 3. Convert to uppercase
result3 = text.upper()
  • 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:

# Temperature conversion program
fahrenheit = float(input("Enter temperature in Fahrenheit: "))
celsius = (fahrenheit - 32) / 1.8
print(f"Temperature in Celsius: {celsius:.2f}")

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:

LOipsetrl:IaAintcs"[dict11eoe[00xns0",:ss]:200,310,42l[0i5]Ms0ot,3d[i02f]0y=,5030,40]

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:

# Creating and using lists
numbers = [1, 2, 3, 4, 5]
numbers.append(6)        # Add 6 at end
numbers.insert(0, 0)     # Add 0 at beginning
print(numbers[2])        # Access 3rd element
numbers.remove(3)        # Remove value 3
  • 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:

name = "Alice"
age = 25
# f-string formatting
message = f"Hello {name}, you are {age} years old"
  • 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:

# Even/Odd checker program
number = int(input("Enter a number: "))
if number % 2 == 0:
    print(f"{number} is even")
else:
    print(f"{number} is odd")

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:

SetUIDSnniyAitfm:oefmSnree{e:srt1teer,{cniO1tcc2p,ie,eo:Dr2ni3a,:{f}t1fi3{,:o,3n}2{s4}1S,,e2t5,}4B,:5}{3,4,5}

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:

# Creating and using sets
fruits = {"apple", "banana", "orange"}
fruits.add("mango")              # Add single item
fruits.update(["grape", "kiwi"]) # Add multiple
fruits.remove("banana")          # Remove item
print(len(fruits))               # Count items
  • 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:

import math
number = 16
result1 = math.sqrt(number)  # Square root
result2 = math.pow(2, 4)     # 2 to power 4
result3 = math.ceil(7.2)     # Round up to 8
  • 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:

# Sum of list elements
numbers = [10, 20, 30, 40, 50]
total = 0
for element in numbers:
    total += element
print(f"Sum of all elements: {total}")

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:

LlC{ieracsne::t(a131LYt,}:ieessb[tD:a1i2,)c,tb=,=NoEMclre]ersnos(raLgiesLti2s)t2?:[1,2,3]

Complete Program:

# Merge lists into dictionary
list1 = ['name', 'age', 'city']
list2 = ['John', 25, 'Mumbai']

if len(list1) == len(list2):
    # Create dictionary using zip
    result_dict = dict(zip(list1, list2))
    print("Dictionary created:", result_dict)
else:
    print("Lists have different lengths, cannot merge")

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:

# Manual dictionary creation
result_dict = {}
for i in range(len(list1)):
    result_dict[list1[i]] = list2[i]

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:

import statistics
data = [10, 20, 30, 40, 50]
avg = statistics.mean(data)      # Calculate average
mid = statistics.median(data)    # Find middle value
  • 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:

SLDtoirociptnigtho:hnra"orhuyeg:lhle{oe'"ahc'h:l1c,ha'real'c:t1e,r'l':2,':1}

Complete Program:

# Character frequency counter
text = input("Enter a string: ")
char_count = {}

for char in text:
    if char in char_count:
        char_count[char] += 1
    else:
        char_count[char] = 1

print("Character frequencies:")
for char, count in char_count.items():
    print(f"'{char}': {count}")

Alternative Method (More Pythonic):

# Using get() method
text = "programming"
char_count = {}

for char in text:
    char_count[char] = char_count.get(char, 0) + 1

print(char_count)

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:

ObjeA--M--cCtetltcmtss:aroohttsildoaomsboedrpy:urlst(_t:()cCe)aasrr:=Car()

Example Code:

class Student:
    def __init__(self, name, age):
        self.name = name  # Attribute
        self.age = age    # Attribute
    
    def display(self):    # Method
        print(f"Name: {self.name}, Age: {self.age}")

# Creating objects
student1 = Student("Alice", 20)
student1.display()
  • 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:

# Print odd numbers from list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

print("Odd numbers in the list:")
for number in numbers:
    if number % 2 != 0:
        print(number, end=" ")

Alternative Methods:

# Method 2: List comprehension
odd_numbers = [num for num in numbers if num % 2 != 0]
print(odd_numbers)

# Method 3: Using filter
odd_numbers = list(filter(lambda x: x % 2 != 0, numbers))
print(odd_numbers)

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:

dFreuefntcLPCuftoraruicolnnoacccnleurtKsleieBvsasoyoaitunwdrnil_oyigotnranad(blsmilooetnegp(Fodsitpueciandnorcetnatfeamiidleon))tneerIifsndu)pen:unctttiivfoainleures

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:

# Function with no parameters
def greet():
    print("Hello, World!")

# Function with parameters and return value
def calculate_area(length, width):
    area = length * width
    return area

# Function with default parameters
def introduce(name, age=18):
    print(f"My name is {name} and I am {age} years old")

# Using functions
greet()
result = calculate_area(5, 3)
print(f"Area: {result}")
introduce("Alice", 25)
introduce("Bob")  # Uses default age

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:

class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age
        print("Student object created")

# Object creation automatically calls constructor
student1 = Student("Alice", 20)
  • 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:

# Find smallest number without min()
numbers = [45, 23, 67, 12, 89, 5, 34]

smallest = numbers[0]  # Assume first is smallest

for i in range(1, len(numbers)):
    if numbers[i] < smallest:
        smallest = numbers[i]

print(f"Smallest number: {smallest}")

Alternative Method:

# Using for loop with list elements
numbers = [45, 23, 67, 12, 89, 5, 34]
smallest = numbers[0]

for num in numbers[1:]:
    if num < smallest:
        smallest = num

print(f"Smallest number: {smallest}")

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:

SSSSSttttteeeeeppppp12345:::::CWSIUrramseivpeateotermeftofid.uliupnenlycetofitfiohulnenesrc/tcpilroaonsgssreasms

Example Module Creation:

File: math_operations.py

# User-defined module
PI = 3.14159

def calculate_circle_area(radius):
    return PI * radius * radius

def calculate_rectangle_area(length, width):
    return length * width

class Calculator:
    def add(self, a, b):
        return a + b
    
    def subtract(self, a, b):
        return a - b

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:

# main.py - Using the module
import math_operations

# Using module functions
radius = 5
area = math_operations.calculate_circle_area(radius)
print(f"Circle area: {area}")

# Using module variables
print(f"PI value: {math_operations.PI}")

# Using module classes
calc = math_operations.Calculator()
result = calc.add(10, 20)
print(f"Addition result: {result}")

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:

PCahriIOelnwnA--M--dh--n-tteetnatesCrneMbCraghalliaaealimeoteatmttrabed(esee(hksus)psd,)o(st:(::,d):e)iassnDgs:A:hoelnegeiremipat(ls)

Example Code:

# Parent class
class Animal:
    def __init__(self, name):
        self.name = name
    
    def eat(self):
        print(f"{self.name} is eating")

# Child class inheriting from Animal
class Dog(Animal):
    def bark(self):
        print(f"{self.name} is barking")

# Using inheritance
my_dog = Dog("Buddy")
my_dog.eat()    # Inherited method
my_dog.bark()   # Own method
  • 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:

from abc import ABC, abstractmethod

# Abstract class
class Shape(ABC):
    @abstractmethod
    def area(self):
        pass
    
    @abstractmethod
    def perimeter(self):
        pass

# Concrete class
class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width
    
    def area(self):
        return self.length * self.width
    
    def perimeter(self):
        return 2 * (self.length + self.width)

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:

MMuullttiFiAMpa-naDltlimoehemmgeCvaaIrhellnilhledIrniMhteatrnhicetera:nce:

Complete Program:

# Multi-level Inheritance Demo
print("=== Multi-level Inheritance ===")

class Animal:
    def __init__(self, name):
        self.name = name
    
    def eat(self):
        print(f"{self.name} can eat")

class Mammal(Animal):  # Inherits from Animal
    def breathe(self):
        print(f"{self.name} breathes air")

class Dog(Mammal):     # Inherits from Mammal (which inherits from Animal)
    def bark(self):
        print(f"{self.name} can bark")

# Using multi-level inheritance
my_dog = Dog("Buddy")
my_dog.eat()     # From Animal (grandparent)
my_dog.breathe() # From Mammal (parent)
my_dog.bark()    # Own method

print("\n=== Multiple Inheritance ===")

class Father:
    def father_method(self):
        print("Method from Father class")

class Mother:
    def mother_method(self):
        print("Method from Mother class")

class Child(Father, Mother):  # Inherits from both Father and Mother
    def child_method(self):
        print("Method from Child class")

# Using multiple inheritance
child = Child()
child.father_method()  # From Father
child.mother_method()  # From Mother
child.child_method()   # Own method

# Checking inheritance
print(f"\nChild inherits from Father: {issubclass(Child, Father)}")
print(f"Child inherits from Mother: {issubclass(Child, Mother)}")

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:

class Student:
    school_name = "ABC School"  # Class variable
    
    def __init__(self, name):
        self.name = name        # Instance variable
    
    # Instance method
    def display_info(self):
        print(f"Student: {self.name}")
    
    # Class method
    @classmethod
    def get_school(cls):
        return cls.school_name
    
    # Static method
    @staticmethod
    def is_adult(age):
        return age >= 18

# Usage
student = Student("Alice")
student.display_info()           # Instance method
print(Student.get_school())      # Class method
print(Student.is_adult(20))      # Static method
  • 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:

# Base class
class Shape:
    def area(self):
        pass

# Different implementations
class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width
    
    def area(self):
        return self.length * self.width

class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius
    
    def area(self):
        return 3.14 * self.radius * self.radius

# Polymorphic behavior
shapes = [Rectangle(5, 3), Circle(4)]

for shape in shapes:
    print(f"Area: {shape.area()}")  # Same method, different results

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:

DgHyAMbnarimimmdaallCPae(ttBase)

Inheritance Types in Hybrid:

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

Complete Program:

# Hybrid Inheritance Demonstration

print("=== Hybrid Inheritance Demo ===")

# Base class (Level 1)
class Animal:
    def __init__(self, name):
        self.name = name
    
    def eat(self):
        print(f"{self.name} can eat")
    
    def sleep(self):
        print(f"{self.name} can sleep")

# Single inheritance (Level 2)
class Mammal(Animal):
    def breathe(self):
        print(f"{self.name} breathes air")
    
    def give_birth(self):
        print(f"{self.name} gives birth to babies")

# Multiple inheritance branches (Level 3)
class Dog(Mammal):
    def bark(self):
        print(f"{self.name} barks: Woof!")
    
    def loyalty(self):
        print(f"{self.name} is loyal to owner")

class Cat(Mammal):
    def meow(self):
        print(f"{self.name} meows: Meow!")
    
    def independence(self):
        print(f"{self.name} is independent")

# Hybrid class - Multiple inheritance (Level 4)
class HybridPet(Dog, Cat):
    def __init__(self, name, breed):
        super().__init__(name)
        self.breed = breed
    
    def play(self):
        print(f"{self.name} loves to play")
    
    def show_info(self):
        print(f"Name: {self.name}, Breed: {self.breed}")

# Creating and using hybrid inheritance
print("\n--- Creating Hybrid Pet ---")
pet = HybridPet("Buddy", "Labrador-Persian Mix")

print("\n--- Methods from Animal (Great-grandparent) ---")
pet.eat()
pet.sleep()

print("\n--- Methods from Mammal (Grandparent) ---")
pet.breathe()
pet.give_birth()

print("\n--- Methods from Dog (Parent 1) ---")
pet.bark()
pet.loyalty()

print("\n--- Methods from Cat (Parent 2) ---")
pet.meow()
pet.independence()

print("\n--- Own Methods ---")
pet.play()
pet.show_info()

print("\n--- Inheritance Chain ---")
print(f"MRO (Method Resolution Order): {HybridPet.__mro__}")

# Checking inheritance relationships
print(f"\nIs HybridPet subclass of Animal? {issubclass(HybridPet, Animal)}")
print(f"Is HybridPet subclass of Dog? {issubclass(HybridPet, Dog)}")
print(f"Is HybridPet subclass of Cat? {issubclass(HybridPet, Cat)}")

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”

Related

Renewable Energy & Emerging Trends in Electronics (4361106) - Summer 2024 Solution
19 mins
Study-Material Solutions Renewable-Energy 4361106 2024 Summer
VLSI (4361102) - Summer 2024 Solution
18 mins
Study-Material Solutions Vlsi 4361102 2024 Summer
Computer Networks & Data Communication (4361101) - Summer 2024 Solution
16 mins
Study-Material Solutions Computer-Networks 4361101 2024 Summer
OOPS & Python Programming (4351108) - Winter 2023 Solution
16 mins
Study-Material Solutions Python Oop 4351108 2023 Winter
Linear Integrated Circuit (4341105) - Winter 2024 Solution
28 mins
Study-Material Solutions Linear-Integrated-Circuit 4341105 2024 Winter
Antenna & Wave Propagation (4341106) - Winter 2024 Solution
21 mins
Study-Material Solutions Antenna Wave-Propagation 4341106 2024 Winter