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 AreaDescription
Web DevelopmentDjango, Flask frameworks
Data ScienceAnalysis and visualization
Machine LearningAI model development
Desktop ApplicationsGUI using Tkinter, PyQt
Game DevelopmentPygame library
AutomationScripting 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:

FeatureDescription
Simple SyntaxEasy to read and write
InterpretedNo compilation needed
Object-OrientedSupports OOP concepts
Dynamic TypingVariables don't need type declaration
Cross-PlatformRuns on multiple OS
Large LibrariesRich standard library
Open SourceFree to use and modify
InteractiveREPL 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:

OperationSyntaxDescription
Creationlist = [1,2,3]Create new list
Accesslist[0]Get element by index
Appendlist.append(4)Add element at end
Insertlist.insert(1,5)Add at specific position
Removelist.remove(2)Remove first occurrence
Poplist.pop()Remove and return last
Slicelist[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:

OperationSyntaxDescription
Creationtuple = (1,2,3)Create new tuple
Accesstuple[0]Get element by index
Counttuple.count(2)Count occurrences
Indextuple.index(3)Find first index
Slicetuple[1:3]Get sub-tuple
Lengthlen(tuple)Get tuple size
Concatenatetuple1 + tuple2Join 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:

MethodSyntaxDescription
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:

MethodExampleDescription
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:

MethodSyntaxDescription
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:

OperationSyntaxDescription
Creationset = {1,2,3}Create new set
Addset.add(4)Add single element
Removeset.remove(2)Remove element (error if not found)
Discardset.discard(2)Remove element (no error)
Union`set1set2`
Intersectionset1 & set2Common elements
Differenceset1 - set2Elements 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:

AspectClassObject
DefinitionBlueprint or templateInstance of class
MemoryNo memory allocatedMemory allocated
ExistenceLogical entityPhysical entity
CreationUsing class keywordUsing 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:

MethodSyntaxDescription
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 TypeSyntaxDescription
Instance Methoddef 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:

MethodSyntaxDescription
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:

AspectDescription
InitializationAutomatically called when object is created
SetupInitialize instance variables with values
MemoryAllocate memory for object attributes
ValidationValidate 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:

AspectDescription
DefinitionBundling data and methods together
Access ControlRestrict direct access to internal data
Data HidingInternal implementation hidden from outside
InterfaceProvide 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:

ConceptDescription
DefinitionClass that cannot be instantiated directly
Abstract MethodsMethods declared but not implemented
ImplementationSubclasses must implement abstract methods
PurposeDefine 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"