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:
| Feature | Description |
|---|---|
| Simple & Easy | Clean, readable syntax |
| Free & Open Source | No cost, community driven |
| Cross-platform | Runs on Windows, Linux, Mac |
| Interpreted | No compilation needed |
| Object-Oriented | Supports classes and objects |
| Large Libraries | Rich standard library |
Mnemonic: "Simple Free Cross Interpreted Object Large"
Question 1(b) [4 marks]
Write applications of python programming language.
Answer:
| Application Area | Examples |
|---|---|
| Web Development | Django, Flask frameworks |
| Data Science | NumPy, Pandas, Matplotlib |
| Machine Learning | TensorFlow, Scikit-learn |
| Desktop GUI | Tkinter, PyQt applications |
| Game Development | Pygame library |
| Automation | Scripting and testing |
Mnemonic: "Web Data Machine Desktop Game Auto"
Question 1(c) [7 marks]
Explain various datatypes in python.
Answer:
| Data Type | Example | Description |
|---|---|---|
| int | x = 5 | Whole numbers |
| float | y = 3.14 | Decimal numbers |
| str | name = "John" | Text data |
| bool | flag = True | True/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:
| Operator | Operation | Example |
|---|---|---|
+ | Addition | 5 + 3 = 8 |
- | Subtraction | 5 - 3 = 2 |
* | Multiplication | 5 * 3 = 15 |
/ | Division | 10 / 3 = 3.33 |
// | Floor Division | 10 // 3 = 3 |
% | Modulus | 10 % 3 = 1 |
** | Exponent | 2 ** 3 = 8 |
Assignment Operators:
| Operator | Example | Equivalent |
|---|---|---|
= | x = 5 | Assign value |
+= | x += 3 | x = x + 3 |
-= | x -= 2 | x = x - 2 |
*= | x *= 4 | x = x * 4 |
Identity Operators:
| Operator | Purpose | Example |
|---|---|---|
is | Same object | x is y |
is not | Different object | x 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:
| Identifier | Valid/Invalid | Reason |
|---|---|---|
| Total Marks | Invalid | Contains space |
| Total_Marks | Valid | Underscore allowed |
| total-Marks | Invalid | Hyphen not allowed |
| Hundred$ | Invalid | $ symbol not allowed |
| _Percentage | Valid | Can start with underscore |
| True | Invalid | Reserved 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:
| Operation | Syntax | Example |
|---|---|---|
| Create | dict_name = {} | student = {} |
| Add | dict[key] = value | student['name'] = 'John' |
| Modify | dict[key] = new_value | student['name'] = 'Jane' |
| Delete | del dict[key] | del student['name'] |
| Access | dict[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:
| Syntax | Description | Example |
|---|---|---|
list[start:stop] | Elements from start to stop-1 | nums[1:4] |
list[:stop] | From beginning to stop-1 | nums[:3] |
list[start:] | From start to end | nums[2:] |
list[::step] | All elements with step | nums[::2] |
list[::-1] | Reverse list | nums[::-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:
| Property | Description |
|---|---|
| Ordered | Items have defined order |
| Changeable | Can modify after creation |
| Duplicates | Allows duplicate values |
| Indexed | Items 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:
| Property | Description |
|---|---|
| Ordered | Items have defined order |
| Unchangeable | Cannot modify after creation |
| Duplicates | Allows duplicate values |
| Indexed | Items 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:
| Operation | Method | Operator | Example |
|---|---|---|---|
| Create Empty | set() | - | s = set() |
| Add Element | add() | - | s.add(5) |
| Remove Element | remove() | - | s.remove(5) |
| Union | union() | ` | ` |
| Intersection | intersection() | & | A.intersection(B) or A & B |
| Difference | difference() | - | A.difference(B) or A - B |
| Symmetric Diff | symmetric_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 Type | Advantage | Use Case |
|---|---|---|
| For Loop | Simpler syntax | When number of iterations known |
| While Loop | More control | When 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:
| Function | Syntax | Purpose | Example |
|---|---|---|---|
| random() | random.random() | Random float 0.0 to 1.0 | 0.7534 |
| randint() | random.randint(a, b) | Random integer a to b | randint(1, 10) |
| choice() | random.choice(seq) | Random element from sequence | choice(['a', 'b', 'c']) |
Code Example:
Python
Mnemonic: "Random Randint Choice"
Question 4(b) [4 marks]
Write the advantages of functions.
Answer:
Function Advantages:
| Advantage | Description |
|---|---|
| Code Reusability | Write once, use multiple times |
| Modularity | Break large program into smaller parts |
| Easy Debugging | Isolate and fix errors easily |
| Readability | Makes code more organized and clear |
| Maintainability | Easy to update and modify |
| Avoid Repetition | Reduces 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 Type | Scope | Access | Example |
|---|---|---|---|
| Local | Inside function only | Within function | def func(): x = 5 |
| Global | Entire program | Anywhere in program | x = 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:
| Component | Purpose | Example |
|---|---|---|
| def | Keyword to define function | def |
| function_name | Name of function | calculate_area |
| parameters | Input values | (length, width) |
| return | Output value | return 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:
| Aspect | Class | Object |
|---|---|---|
| Definition | Blueprint/template | Instance of class |
| Memory | No memory allocated | Memory allocated |
| Creation | Defined using class keyword | Created using class name |
| Attributes | Defined but not initialized | Have actual values |
| Example | class 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:
| Purpose | Description |
|---|---|
| Initialize Objects | Set initial values to attributes |
| Automatic Execution | Called automatically when object created |
| Memory Setup | Allocate memory for object attributes |
| Default Values | Provide default values to attributes |
Types of Constructors:
| Type | Description | Example |
|---|---|---|
| Default | No parameters | def __init__(self): |
| Parameterized | Takes parameters | def __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:
| Purpose | Description |
|---|---|
| Data Hiding | Hide internal implementation details |
| Data Protection | Protect data from unauthorized access |
| Controlled Access | Provide controlled access through methods |
| Code Security | Prevent accidental modification of data |
| Modularity | Keep 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:
| Level | Class | Inherits From | Access To |
|---|---|---|---|
| Level 1 | GrandPa | None | Own methods |
| Level 2 | Parent | GrandPa | GrandPa + Own methods |
| Level 3 | Child | Parent | GrandPa + 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:
- Single: Mammal ← Animal, Bird ← Animal, Dog ← Mammal
- Multiple: FlyingDog ← Dog + Bird
- Multilevel: FlyingDog ← Dog ← Mammal ← Animal
- 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"