OOPS & Python Programming (4351108) - Winter 2024 Solution

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

Question 1(a) [3 marks]

List out features of python programming language.

Answer:

FeatureDescription
Simple & EasyClean, readable syntax
Free & Open SourceNo cost, community driven
Cross-platformRuns on Windows, Linux, Mac
InterpretedNo compilation needed
Object-OrientedSupports classes and objects
Large LibrariesRich standard library

Mnemonic: "Simple Free Cross Interpreted Object Large"


Question 1(b) [4 marks]

Write applications of python programming language.

Answer:

Application AreaExamples
Web DevelopmentDjango, Flask frameworks
Data ScienceNumPy, Pandas, Matplotlib
Machine LearningTensorFlow, Scikit-learn
Desktop GUITkinter, PyQt applications
Game DevelopmentPygame library
AutomationScripting and testing

Mnemonic: "Web Data Machine Desktop Game Auto"


Question 1(c) [7 marks]

Explain various datatypes in python.

Answer:

Data TypeExampleDescription
intx = 5Whole numbers
floaty = 3.14Decimal numbers
strname = "John"Text data
boolflag = TrueTrue/False values
list[1, 2, 3]Ordered, mutable
tuple(1, 2, 3)Ordered, immutable
dict{"a": 1}Key-value pairs
set{1, 2, 3}Unique elements

Code Example:

Python

Mnemonic: "Integer Float String Boolean List Tuple Dict Set"


Question 1(c OR) [7 marks]

Explain arithmetic, assignment, and identity operators with example.

Answer:

Arithmetic Operators:

OperatorOperationExample
+Addition5 + 3 = 8
-Subtraction5 - 3 = 2
*Multiplication5 * 3 = 15
/Division10 / 3 = 3.33
//Floor Division10 // 3 = 3
%Modulus10 % 3 = 1
**Exponent2 ** 3 = 8

Assignment Operators:

OperatorExampleEquivalent
=x = 5Assign value
+=x += 3x = x + 3
-=x -= 2x = x - 2
*=x *= 4x = x * 4

Identity Operators:

OperatorPurposeExample
isSame objectx is y
is notDifferent objectx is not y

Code Example:

Python

Mnemonic: "Add Assign Identity"


Question 2(a) [3 marks]

Which of the following identifier names are invalid? (i) Total Marks (ii)Total_Marks (iii)total-Marks (iv) Hundred$ (v) _Percentage (vi) True

Answer:

IdentifierValid/InvalidReason
Total MarksInvalidContains space
Total_MarksValidUnderscore allowed
total-MarksInvalidHyphen not allowed
Hundred$Invalid$ symbol not allowed
_PercentageValidCan start with underscore
TrueInvalidReserved keyword

Invalid identifiers: Total Marks, total-Marks, Hundred$, True

Mnemonic: "Space Hyphen Dollar Keyword = Invalid"


Question 2(b) [4 marks]

Write a program to find a maximum number among the given three numbers.

Answer:

Python

Alternative using max() function:

Python

Mnemonic: "Input Compare Display"


Question 2(c) [7 marks]

Explain dictionaries in Python. Write statements to add, modify, and delete elements in a dictionary.

Answer:

Dictionary is a collection of key-value pairs that is ordered, changeable, and does not allow duplicate keys.

Operations Table:

OperationSyntaxExample
Createdict_name = {}student = {}
Adddict[key] = valuestudent['name'] = 'John'
Modifydict[key] = new_valuestudent['name'] = 'Jane'
Deletedel dict[key]del student['name']
Accessdict[key]print(student['name'])

Code Example:

Python

Dictionary Properties:

  • Ordered: Maintains insertion order (Python 3.7+)
  • Changeable: Can modify after creation
  • No Duplicates: Keys must be unique

Mnemonic: "Key-Value Ordered Changeable Unique"


Question 2(a OR) [3 marks]

Write a program to display the following pattern.

Answer:

Python

Output:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Mnemonic: "Outer Row Inner Column Print"


Question 2(b OR) [4 marks]

Write a program to find the sum of digits of an integer number, input by the user.

Answer:

Python

Alternative Method:

Python

Mnemonic: "Input Extract Sum Display"


Question 2(c OR) [7 marks]

Explain slicing and concatenation operation on list.

Answer:

List Slicing: Extracting portion of list using [start:stop:step] syntax.

Slicing Syntax Table:

SyntaxDescriptionExample
list[start:stop]Elements from start to stop-1nums[1:4]
list[:stop]From beginning to stop-1nums[:3]
list[start:]From start to endnums[2:]
list[::step]All elements with stepnums[::2]
list[::-1]Reverse listnums[::-1]

Concatenation: Joining two or more lists using + operator or extend() method.

Code Example:

Python

Key Points:

  • Slicing: Creates new list without modifying original
  • Concatenation: Combines lists into single list
  • Negative indexing: list[-1] gives last element

Mnemonic: "Slice Extract Concat Join"


Question 3(a) [3 marks]

Define a list in Python. Write name of the function used to add an element to the end of a list.

Answer:

List Definition: A list is an ordered collection of items that is changeable and allows duplicate values.

Properties Table:

PropertyDescription
OrderedItems have defined order
ChangeableCan modify after creation
DuplicatesAllows duplicate values
IndexedItems accessed by index

Function to add element: append()

Example:

Python

Mnemonic: "List Append End"


Question 3(b) [4 marks]

Define a tuple in Python. Write statement to access last element of a tuple.

Answer:

Tuple Definition: A tuple is an ordered collection of items that is unchangeable and allows duplicate values.

Properties Table:

PropertyDescription
OrderedItems have defined order
UnchangeableCannot modify after creation
DuplicatesAllows duplicate values
IndexedItems accessed by index

Accessing Last Element:

Python

Mnemonic: "Tuple Unchangeable Negative Index"


Question 3(c) [7 marks]

Write statements for following set operations: create empty set, add an element to a set, remove an element from set, Union of two sets, Intersection of two sets, Difference between two sets and symmetric difference between two sets.

Answer:

Set Operations Table:

OperationMethodOperatorExample
Create Emptyset()-s = set()
Add Elementadd()-s.add(5)
Remove Elementremove()-s.remove(5)
Unionunion()``
Intersectionintersection()&A.intersection(B) or A & B
Differencedifference()-A.difference(B) or A - B
Symmetric Diffsymmetric_difference()^A.symmetric_difference(B) or A ^ B

Code Example:

Python

Mnemonic: "Create Add Remove Union Intersect Differ Symmetric"


Question 3(a OR) [3 marks]

Define a string in Python. Using example illustrate (i) How to create a string. (ii) Accessing individual characters using indexing.

Answer:

String Definition: A string is a sequence of characters enclosed in quotes (single or double).

(i) Creating String:

Python

(ii) Accessing Characters:

Python

Mnemonic: "String Quotes Index Access"


Question 3(b OR) [4 marks]

Explain list traversing using for loop and while loop.

Answer:

List Traversing means visiting each element of list one by one.

For Loop Traversing:

Python

While Loop Traversing:

Python

Comparison Table:

Loop TypeAdvantageUse Case
For LoopSimpler syntaxWhen number of iterations known
While LoopMore controlWhen condition-based iteration needed

Mnemonic: "For Simple While Control"


Question 3(c OR) [7 marks]

Write a program to create a dictionary with the roll number, name, and marks of n students and display the names of students who have scored marks above 75.

Answer:

Python

Sample Output:

Enter number of students: 2

Enter details for student 1:
Roll number: 101
Name: John
Marks: 80

Enter details for student 2:
Roll number: 102
Name: Alice
Marks: 70

Students with marks above 75:
------------------------------
Name: John, Marks: 80.0

Total high performers: 1

Mnemonic: "Input Store Filter Display"


Question 4(a) [3 marks]

Write any three functions available in random module. Write syntax and example of each function.

Answer:

Random Module Functions:

FunctionSyntaxPurposeExample
random()random.random()Random float 0.0 to 1.00.7534
randint()random.randint(a, b)Random integer a to brandint(1, 10)
choice()random.choice(seq)Random element from sequencechoice(['a', 'b', 'c'])

Code Example:

Python

Mnemonic: "Random Randint Choice"


Question 4(b) [4 marks]

Write the advantages of functions.

Answer:

Function Advantages:

AdvantageDescription
Code ReusabilityWrite once, use multiple times
ModularityBreak large program into smaller parts
Easy DebuggingIsolate and fix errors easily
ReadabilityMakes code more organized and clear
MaintainabilityEasy to update and modify
Avoid RepetitionReduces duplicate code

Example:

Python

Mnemonic: "Reuse Modular Debug Read Maintain Avoid"


Question 4(c) [7 marks]

Write a program that asks the user for a string and prints out the location of each 'a' in the string.

Answer:

Python

Sample Output:

Enter a string: Python Programming

Character 'a' found at positions: [12]
Detailed locations:
Position 12: 'a'

Alternative approach:
'a' found at position 12

Enhanced Version:

Python

Mnemonic: "Input Loop Check Store Display"


Question 4(a OR) [3 marks]

Explain local and global variables.

Answer:

Variable Scope Types:

Variable TypeScopeAccessExample
LocalInside function onlyWithin functiondef func(): x = 5
GlobalEntire programAnywhere in programx = 5 (outside function)

Code Example:

Python

Global Keyword:

Python

Mnemonic: "Local Inside Global Everywhere"


Question 4(b OR) [4 marks]

Explain creation and use of user defined function with example.

Answer:

Function Creation Syntax:

Python

Function Components:

ComponentPurposeExample
defKeyword to define functiondef
function_nameName of functioncalculate_area
parametersInput values(length, width)
returnOutput valuereturn result

Example:

Python

Mnemonic: "Define Call Return Parameter"


Question 4(c OR) [7 marks]

Write a program to create a user defined function calcFact() to calculate and display the factorial of a number passed as an argument.

Answer:

Python

Recursive Version:

Python

Sample Output:

Enter a number: 5
Factorial of 5 is: 120

Testing with different values:
calcFact(0) = 1
calcFact(1) = 1
calcFact(5) = 120
calcFact(10) = 3628800
calcFact(-3) = Factorial is not defined for negative numbers

Mnemonic: "Define Check Loop Multiply Return"


Question 5(a) [3 marks]

Give difference between class and object.

Answer:

Class vs Object Comparison:

AspectClassObject
DefinitionBlueprint/templateInstance of class
MemoryNo memory allocatedMemory allocated
CreationDefined using class keywordCreated using class name
AttributesDefined but not initializedHave actual values
Exampleclass Car:my_car = Car()

Code Example:

Python

Mnemonic: "Class Blueprint Object Instance"


Question 5(b) [4 marks]

State the purpose of a constructor in a class.

Answer:

Constructor Purpose:

PurposeDescription
Initialize ObjectsSet initial values to attributes
Automatic ExecutionCalled automatically when object created
Memory SetupAllocate memory for object attributes
Default ValuesProvide default values to attributes

Types of Constructors:

TypeDescriptionExample
DefaultNo parametersdef __init__(self):
ParameterizedTakes parametersdef __init__(self, name):

Example:

Python

Mnemonic: "Initialize Automatic Memory Default"


Question 5(c) [7 marks]

Write a program to create a class "Student" with attributes such as name, roll number, and marks. Implement method to display student information. Create object of the student class and show how to use method.

Answer:

Python

Sample Output:

Creating Student Objects:

=== Student 1 Details ===
------------------------------
STUDENT INFORMATION
------------------------------
Name: John Doe
Roll Number: 101
Marks: 85
------------------------------
Grade: A

=== Student 2 Details ===
------------------------------
STUDENT INFORMATION
------------------------------
Name: Alice Smith
Roll Number: 102
Marks: 92
------------------------------
Grade: A+

Class Components:

  • Attributes: name, roll_number, marks
  • Constructor: __init__() method
  • Methods: display_info(), calculate_grade(), display_grade()
  • Objects: student1, student2, student3

Mnemonic: "Class Attributes Constructor Methods Objects"


Question 5(a OR) [3 marks]

State the purpose of encapsulation.

Answer:

Encapsulation Purpose:

PurposeDescription
Data HidingHide internal implementation details
Data ProtectionProtect data from unauthorized access
Controlled AccessProvide controlled access through methods
Code SecurityPrevent accidental modification of data
ModularityKeep related data and methods together

Implementation Example:

Python

Benefits:

  • Security: Data cannot be accessed directly
  • Maintenance: Easy to modify internal implementation
  • Validation: Can add validation in getter/setter methods

Mnemonic: "Hide Protect Control Secure Modular"


Question 5(b OR) [4 marks]

Explain multilevel inheritance.

Answer:

Multilevel Inheritance is when a class inherits from another class, which in turn inherits from another class, forming a chain.

Structure Diagram:

goat

Characteristics Table:

LevelClassInherits FromAccess To
Level 1GrandPaNoneOwn methods
Level 2ParentGrandPaGrandPa + Own methods
Level 3ChildParentGrandPa + Parent + Own

Code Example:

Python

Mnemonic: "Chain Inherit Level Access"


Question 5(c OR) [7 marks]

Write a Python program to demonstrate working of hybrid inheritance.

Answer:

Hybrid Inheritance combines multiple types of inheritance (single, multiple, multilevel) in one program.

Structure Diagram:

goat

Code Example:

Python

Sample Output:

=== Hybrid Inheritance Demo ===

1. Creating regular dog:
Animal Buddy created
Buddy the Retriever is barking
Buddy is guarding the house

2. Creating regular bird:
Animal Eagle created
Eagle is flying with 200cm wings
Eagle lays eggs

3. Creating magical flying dog:
Animal Superdog created
Animal Superdog created
Magical Superdog created with both mammal and bird features!

Superdog's Abilities:
-------------------------
Superdog is eating
Superdog is sleeping
Superdog gives birth to live babies
Superdog the Husky is barking
Superdog is guarding the house
Superdog is flying with 150cm wings
Superdog lays eggs
Superdog is flying and barking at the same time!

Inheritance Types in This Example:

  1. Single: Mammal ← Animal, Bird ← Animal, Dog ← Mammal
  2. Multiple: FlyingDog ← Dog + Bird
  3. Multilevel: FlyingDog ← Dog ← Mammal ← Animal
  4. Hybrid: Combination of all above

Key Features:

  • Multiple Parent Classes: FlyingDog inherits from both Dog and Bird
  • Method Resolution Order: Python follows MRO to resolve method conflicts
  • Super() Usage: Proper initialization of parent classes
  • Combined Functionality: Access to methods from all parent classes

Mnemonic: "Hybrid Multiple Single Multilevel Combined"