0% found this document useful (0 votes)
2 views34 pages

Python Programming Sample Answers

Uploaded by

harshitakusanale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views34 pages

Python Programming Sample Answers

Uploaded by

harshitakusanale
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1BPLC205B - Python Programming - Frequently asked questions

Q1. What is Object-Oriented Programming (OOP)? Explain the concepts of Class and Object with a
suitable Python example.

Introduction: As software systems become larger and more complex, managing programs using only
functions becomes difficult. To overcome this problem, programmers use Object-Oriented Programming
(OOP).

Object-Oriented Programming is a programming approach in which programs are organized around objects
rather than individual functions.

Python is an Object-Oriented Programming language and provides features such as classes, objects,
inheritance, and polymorphism.

Definition of OOP: Object-Oriented Programming (OOP) is a programming paradigm that represents real-
world entities as objects containing data and methods.

An object generally consists of:

1. Attributes (Data) – Characteristics of an object.


2. Methods (Functions) – Actions performed by an object.

Example

Consider a Student.
Attributes:
• Name
• USN
• Marks
Methods:
• Study
• Attend Class
• Display Details

Similarly, in Python, a student can be represented as an object.

Features of OOP

1. Encapsulation: Combining data and methods into a single unit called a class.
2. Inheritance: Creating a new class from an existing class.
3. Polymorphism: One interface can have multiple forms.
4. Abstraction: Showing essential information while hiding implementation details.

Class: A Class is a blueprint or template used to create objects.

It specifies:

• What data an object will contain.


• What operations an object can perform.

Syntax
class ClassName:
pass

Example

class Student:
pass

Here, Student is a class.

Object: An Object is an instance of a class. Objects occupy memory and store actual values.

Syntax

object_name = ClassName()

Example

s1 = Student()

Here, s1 is an object of class Student.

Example Program

class Student:

def __init__(self, name, usn):


[Link] = name
[Link] = usn

def display(self):
print("Name :", [Link])
print("USN :", [Link])

s1 = Student("Rahul", "2HB26CS001")

[Link]()

Output

Name : Rahul
USN : 2HB26CS001

Explanation

Step 1: A class named Student is created.


Step 2: The constructor initializes the attributes.
[Link] = name
[Link] = usn
Step 3: An object s1 is created.
s1 = Student(...)
Step 4: The method display() displays the data.
Advantages of OOP

1. Code reusability.
2. Better organization.
3. Easy maintenance.
4. Modular design.
5. Models real-world entities effectively.

Conclusion: Object-Oriented Programming organizes software around objects. A class acts as a blueprint,
and objects are instances of that blueprint. OOP improves code reusability, readability, and maintainability.

Q2. Define a Class and an Object. Illustrate the creation of objects from a class with a suitable
example.

Introduction: Classes and objects are the fundamental building blocks of Object-Oriented Programming.
Every OOP program revolves around creating and using objects.

Class: A Class is a user-defined data type that serves as a blueprint for creating objects. A class contains:

• Attributes (data)
• Methods (functions)

Example

class Car:
pass

Here, Car is a class.

Object: An Object is an instance of a class. Objects contain actual data and can access methods defined inside
the class.

Example

c1 = Car()

Here, c1 is an object.

Steps for Creating Objects

Step 1: Define a class.


Step 2: Define attributes and methods.
Step 3: Create an object using the class name.
Step 4: Access attributes and methods using the dot operator.

Example Program

class Car:

def __init__(self, brand):


[Link] = brand

def display(self):
print("Brand :", [Link])

c1 = Car("Toyota")

[Link]()

Output

Brand : Toyota

Explanation

• Car is a class.
• brand is an attribute.
• display() is a method.
• c1 is an object.
• The object accesses the method using the dot operator.

Conclusion:A class defines the structure of objects, while objects represent actual entities created from the
class.

Q3. What is Object Instantiation? Explain the process of creating objects from a class with a suitable
example program.

Introduction: The primary purpose of defining a class is to create objects. The process of creating objects
from a class is called Object Instantiation.

Object Instantiation: Object Instantiation is the process of creating an object from a class.

When an object is created:

1. Memory is allocated.
2. The constructor (__init__()) is called automatically.
3. Attributes are initialized.

Steps in Object Instantiation

Step 1: Define a class.


Step 2: Define a constructor.
Step 3: Create an object using:
object_name = ClassName()
Step 4: Access attributes and methods.

Example Program

class Employee:
def __init__(self, name, salary):
[Link] = name
[Link] = salary

def display(self):
print("Name :", [Link])
print("Salary :", [Link])

e1 = Employee("Ravi", 50000)

[Link]()

Output

Name : Ravi
Salary : 50000

Explanation

• Employee is the class.


• e1 is the object.
• Object creation automatically invokes the constructor.
• Attributes are initialized and displayed.

Conclusion: Object instantiation creates usable objects from a class and allows them to store and process
data.

Q4. Explain the role of the __init__() method in Python classes with an example.

Introduction: Whenever an object is created, some initial values need to be assigned to its attributes. Python
provides a special method called __init__() for this purpose.

Definition: The __init__() method is a special method known as the constructor. It is automatically
executed whenever an object is created.

Role of __init__()

1. Initializes object attributes.


2. Assigns initial values.
3. Executes setup code.
4. Ensures every object starts with valid data.

Syntax

def __init__(self, parameters):


statements

Example Program
class Book:

def __init__(self, title, author):


[Link] = title
[Link] = author

def display(self):
print("Title :", [Link])
print("Author:", [Link])

b1 = Book("Python Programming", "Guido")

[Link]()

Output

Title : Python Programming


Author: Guido

Explanation

• Constructor receives title and author.


• Values are stored in object attributes.
• Constructor executes automatically during object creation.

Conclusion: The __init__() method initializes objects and ensures that all attributes receive appropriate
values during creation.

Q5. What are Attributes in Python Classes? Explain Instance Attributes with a suitable example.

Introduction: Objects store information about real-world entities. This information is represented using
variables called attributes.

Attributes: Attributes are variables associated with a class or object that store data. Example:

A Student object may contain:

• Name
• USN
• Marks

Types of Attributes

1. Class Attributes: Shared by all objects.

2. Instance Attributes: Unique to each object. Defined using: self.attribute_name. Instance


attributes belong to a specific object.

Each object maintains its own copy of these attributes.


Example Program

class Student:

def __init__(self, name, marks):


[Link] = name
[Link] = marks

s1 = Student("Rahul", 85)

s2 = Student("Anita", 92)

print([Link], [Link])

print([Link], [Link])

Output

Rahul 85
Anita 92

Explanation

• name and marks are instance attributes.


• s1 and s2 have separate values.
• Changing one object's attributes does not affect the other.

Advantages of Instance Attributes

1. Store object-specific information.


2. Provide data independence.
3. Support multiple objects with different values.

Conclusion: Attributes represent the properties of objects. Instance attributes are unique to each object and
enable objects to store their own data independently.

Q6. Explain how attributes are accessed and modified using the dot (.) operator.

Introduction: In Object-Oriented Programming, objects store data in the form of attributes. After creating an
object, we often need to read or modify these attributes. Python provides the dot (.) operator for this
purpose.

The dot operator is one of the most commonly used operators in OOP because it allows access to an object's
data and methods.

Dot (.) Operator: The dot operator is used to access:


1. Attributes of an object
2. Methods of an object

General Syntax
1. Accessing an Attribute

object_name.attribute_name

2. Modifying an Attribute

object_name.attribute_name = new_value

3. Calling a Method

object_name.method_name()

Accessing Attributes: When an object is created, its attributes store values. Example:

[Link] - retrieves the value stored in the attribute name.

Modifying Attributes: The value of an attribute can be changed after object creation.

Example:

[Link] = 95 - updates the value stored in marks.

Example Program

class Student:

def __init__(self, name, marks):


[Link] = name
[Link] = marks

s1 = Student("Rahul", 85)

print("Before Modification")
print("Name :", [Link])
print("Marks:", [Link])

[Link] = 95

print("After Modification")
print("Marks:", [Link])

Output

Before Modification
Name : Rahul
Marks: 85

After Modification
Marks: 95

Explanation
Step 1: A class Student is created.
Step 2: An object s1 is created.
s1 = Student("Rahul",85)
Step 3: Attributes are accessed using:
[Link]
[Link]
Step 4: The marks attribute is modified.
[Link] = 95
Step 5: The updated value is displayed.

Advantages of Dot Operator

1. Simple and easy to use.


2. Provides direct access to object data.
3. Allows modification of attributes.
4. Used for method invocation.

Conclusion: The dot operator is used to access and modify object attributes and methods. It provides a
simple way to interact with objects in Python.

Q7. Write a Python program to define a class Student with attributes USN, Name, and Marks and display
the details.

Introduction: A class can be used to represent real-world entities. A student can be modeled using attributes
such as USN, Name, and Marks. These attributes store information about each student.

Problem Statement: Create a class named Student containing: USN, Name, Marks. Display the student
details using a method.

Program

class Student:

def __init__(self, usn, name, marks):


[Link] = usn
[Link] = name
[Link] = marks

def display(self):
print("USN :", [Link])
print("Name :", [Link])
print("Marks :", [Link])

s1 = Student("2HB26CS001", "Rahul", 85)


[Link]()

Output

USN : 2HB26CS001
Name : Rahul
Marks : 85

Explanation

Step 1: The class Student is defined.


Step 2: The constructor initializes three attributes:
[Link]
[Link]
[Link]
Step 3: The method display() prints the details.
Step 4: An object is created.
s1 = Student(...)
Step 5: The method is called using:
[Link]()

Applications

1. Student Information System


2. College Database
3. Examination Management System

Conclusion: Classes can be used to represent students and store their details efficiently using attributes and
methods.

Q8. What are Methods in Python Classes? Explain with a suitable example.

Introduction: Objects contain both data and behavior. Data is stored in attributes, while behavior is
implemented using methods. Methods define what actions an object can perform.

Definition: A method is a function defined inside a class.

Methods are used to:

• Process object data


• Display information
• Perform calculations
• Modify attributes

Syntax

class ClassName:
def method_name(self):

statements - The first parameter is usually self.

Why are Methods Important? Methods allow objects to:

1. Perform tasks.
2. Manipulate data.
3. Encapsulate functionality.
4. Improve code organization.

Example Program

class Calculator:

def add(self, a, b):


return a + b

calc = Calculator()

result = [Link](10, 20)

print("Sum =", result)

Output

Sum = 30

Explanation

Step 1: A class Calculator is created.


Step 2: The method add() performs addition.
Step 3: An object calc is created.
Step 4: The method is called.
[Link](10,20)
Step 5: The result is displayed.

Advantages of Methods

1. Improve modularity.
2. Organize related operations.
3. Increase code reusability.
4. Support encapsulation.

Conclusion: Methods define the behavior of objects and enable them to perform useful operations on
data.
Q9. Explain the significance of the self parameter in Python methods.

Introduction: One unique feature of Python classes is the use of the self parameter. Every instance method
in a class contains self as its first parameter. self plays a very important role in OOP.

What is self? self is a reference to the current object. It allows an object to:

• Access its own attributes.

• Access its own methods.

Why is self Needed?

Suppose there are multiple objects:

s1
s2
s3

Python must know which object's attributes are being accessed. The self parameter provides this
information.

Example Program

class Student:

def __init__(self, name):


[Link] = name

def display(self):
print("Name :", [Link])

s1 = Student("Rahul")

[Link]()

Output

Name : Rahul

Explanation

Constructor

[Link] = name - stores the value inside the current object.

Method

print([Link]) - retrieves the value from the same object.

Internal Working

When Python executes:


[Link]() - it internally converts it into:

[Link](s1) - Thus, self refers to s1.

Advantages of self

1. Identifies the current object.


2. Accesses instance attributes.
3. Accesses instance methods.
4. Supports multiple objects.

Conclusion: The self parameter represents the current object and enables methods to access the object's
own data and functionality.

Q10. Develop a Python class with methods to perform addition and subtraction of two numbers.

Introduction: Methods can be used to perform arithmetic operations. A class can group related operations
together, making the program more organized and reusable.

Problem Statement: Develop a class that contains methods for: Addition, Subtraction of two numbers.

Program

class Calculator:

def add(self, a, b):


return a + b

def subtract(self, a, b):


return a - b

calc = Calculator()

print("Addition =", [Link](20, 10))

print("Subtraction =", [Link](20, 10))

Output

Addition = 30
Subtraction = 10

Explanation

Step 1: A class Calculator is defined.


Step 2: The method add() returns the sum.
return a + b
Step 3: The method subtract() returns the difference.
return a - b
Step 4: An object calc is created.
Step 5: Methods are called using the dot operator.
[Link](20,10)

[Link](20,10)

Advantages

1. Groups related operations.


2. Promotes code reuse.
3. Demonstrates the use of methods.
4. Improves program structure.

Conclusion: Methods inside a class can perform arithmetic operations efficiently. Grouping operations within
a class improves organization and supports the principles of Object-Oriented Programming.

Q11. Explain how objects can be passed as arguments to functions with a suitable example.

Introduction: In Python, everything is treated as an object. Similar to integers, strings, and lists, objects
created from user-defined classes can also be passed as arguments to functions. This feature improves code
reusability and enables functions to operate directly on object data.

Objects as Arguments: When an object is passed to a function, the function receives a reference to that
object. The function can then access the object's attributes and methods using the dot (.) operator.

General Syntax

function_name(object_name)

Inside the function:

[Link]

Why Pass Objects as Arguments?

1. To process object data.


2. To compare objects.
3. To perform calculations using object attributes.
4. To improve modularity and code reuse.

Example Program

class Student:

def __init__(self, name, marks):


[Link] = name
[Link] = marks
def display(student):
print("Student Name :", [Link])
print("Student Marks:", [Link])

s1 = Student("Rahul", 85)

display(s1)

Output

Student Name : Rahul


Student Marks: 85

Explanation

Step 1: A class named Student is created.


class Student:
Step 2: The constructor initializes name and marks.
[Link] = name
[Link] = marks
Step 3: A function display() is defined that accepts an object.
def display(student):
Step 4: The function accesses the attributes using the dot operator.
[Link]
[Link]
Step 5: The object s1 is passed to the function.
display(s1)

Advantages

• Promotes code reusability.


• Supports modular programming.
• Simplifies object processing.

Conclusion: Objects can be passed as arguments to functions in Python, allowing functions to access and
manipulate object data effectively.

Q12. Illustrate instances as parameters in Python with a suitable example.

Introduction: An instance is another name for an object. Python allows instances of a class to be passed as
parameters to functions or methods. This capability is useful for performing operations involving objects.

Instances as Parameters: When an instance is passed as a parameter, the receiving function can access the
attributes and methods of that instance.
Example: Consider a point on a graph represented by coordinates (x, y). A function can receive the point
object and calculate its distance from the origin.

Example Program

class Point:

def __init__(self, x, y):


self.x = x
self.y = y

def distance(point):
d = (point.x**2 + point.y**2)**0.5
return d

p1 = Point(3, 4)

print("Distance =", distance(p1))

Output

Distance = 5.0

Explanation

Step 1: The class Point stores x and y coordinates.


Step 2: The function distance() receives an instance as a parameter.
def distance(point):
Step 3: The function accesses instance attributes.
point.x
point.y
Step 4: Distance is calculated using the distance formula.
Step 5: The instance p1 is passed to the function.
distance(p1)

Applications

1. Geometry calculations.
2. Scientific computations.
3. Data processing applications.

Conclusion: Instances can be passed as parameters to functions, enabling efficient processing of object data.

Q13. Write a Python program where an object of one class is passed to a function for processing.

Introduction: A common application of Object-Oriented Programming is passing objects to functions for


processing. The function receives the object and performs operations using its attributes.
Example Program

class Employee:

def __init__(self, name, salary):


[Link] = name
[Link] = salary

def process(emp):

annual_salary = [Link] * 12

print("Employee Name :", [Link])


print("Annual Salary :", annual_salary)

e1 = Employee("Ravi", 50000)

process(e1)

Output

Employee Name : Ravi


Annual Salary : 600000

Explanation

Step 1: The class Employee contains employee details.


Step 2: The object e1 is created.
e1 = Employee("Ravi",50000)
Step 3: The function process() accepts the object.
process(e1)
Step 4: The function accesses employee attributes.
[Link]
[Link]
Step 5: Annual salary is calculated and displayed.

Advantages

• Simplifies processing of object data.


• Improves modularity.
• Enhances code reuse.

Conclusion: Passing objects to functions allows efficient manipulation and processing of object attributes.

Q14. Explain the purpose of the __str__() method with a suitable example.
Introduction: When an object is printed directly, Python displays its memory address. Such output is not
meaningful to users. To provide a readable representation of an object, Python offers the special method
__str__().

Definition of __str__(): The __str__() method is a special method that returns a string representation of an
object. Whenever an object is printed using:

print(object_name) - Python automatically calls:

object_name.__str__()

Purpose of __str__()

1. Provides meaningful output.


2. Improves readability.
3. Helps debugging.
4. Makes programs user-friendly.

Example Program

class Student:

def __init__(self, name, marks):


[Link] = name
[Link] = marks

def __str__(self):
return "Name: " + [Link] + ", Marks: " + str([Link])

s1 = Student("Anita", 92)

print(s1)

Output

Name: Anita, Marks: 92

Explanation

Without __str__() - Python displays:

<__main__.Student object at 0x123456>

With __str__() - Python displays:

Name: Anita, Marks: 92 - The method converts object data into a readable string.

Advantages

1. Improves object representation.


2. Useful in reports and displays.
3. Makes output understandable.

Conclusion: The __str__() method provides a user-friendly string representation of an object, improving
readability and usability.

Q15. How can an object be converted into a readable string representation? Illustrate with an example.

Introduction: Objects are internally represented by memory locations. However, users generally require
meaningful information rather than memory addresses. Python uses the __str__() method to convert objects
into readable string representations.

Converting Objects to Strings: The conversion is achieved by defining the __str__() method inside a class.

Syntax

def __str__(self):

return string

The returned value must always be a string.

Example Program

class Book:

def __init__(self, title, author):


[Link] = title
[Link] = author

def __str__(self):
return "Book: " + [Link] + \
", Author: " + [Link]

b1 = Book("Python Programming", "Guido")

print(b1)

Output

Book: Python Programming, Author: Guido

Explanation

Step 1: A class Book is created.


Step 2: The constructor initializes title and author.
Step 3: The __str__() method returns a descriptive string.
Step 4: When print(b1) is executed, Python automatically calls b1.__str__().
Step 5: The returned string is displayed.
Benefits

1. Improves readability.
2. Facilitates debugging.
3. Provides meaningful object information.
4. Enhances user interaction.

Conclusion: Objects can be converted into readable string representations by implementing the __str__()
method. This method allows users to view meaningful information instead of memory addresses.

Q16. Explain instances as return values with a suitable Python program.

Introduction: In Python, functions can return simple values such as integers, strings, and lists. Similarly,
functions can also return objects (instances) of classes. This feature allows functions to create and return
newly constructed objects.

Instances as Return Values: An instance is an object created from a class. A function may create an object
inside its body and return it to the calling function.

General Syntax

def function_name():
obj = ClassName()
return obj

Why Return Objects?

1. To create new objects dynamically.


2. To improve modularity.
3. To simplify object creation.
4. To reuse object creation logic.

Example Program

class Point:

def __init__(self, x, y):


self.x = x
self.y = y

def create_point():
p = Point(10, 20)
return p

p1 = create_point()
print("X =", p1.x)
print("Y =", p1.y)

Output

X = 10
Y = 20

Explanation

Step 1: The class Point is defined with attributes x and y.


Step 2: The function create_point() creates an object.
p = Point(10,20)
Step 3: The object is returned.
return p
Step 4: The returned object is assigned to p1.
p1 = create_point()
Step 5: The object's attributes are accessed using the dot operator.

Advantages

1. Supports object creation through functions.


2. Improves code readability.
3. Promotes modular programming.

Conclusion: Instances can be returned from functions just like other values. This allows programs to create
and use objects efficiently.

Q17. Write a Python function that creates and returns an object of a class.

Introduction: A function can create an object of a class and return it to the caller. This technique is commonly
used in object-oriented programming to encapsulate object creation.

Program

class Student:

def __init__(self, name):


[Link] = name

def create_student():

s = Student("Rahul")

return s

s1 = create_student()
print("Student Name:", [Link])

Output

Student Name: Rahul

Explanation

Step 1: The class Student is created.


Step 2: The function create_student() creates an object.
s = Student("Rahul")
Step 3: The object is returned.
return s
Step 4: The returned object is stored in s1.
s1 = create_student()
Step 5: The attribute is displayed.
print([Link])

Applications

1. Factory functions.
2. Object generation systems.
3. Data modeling applications.

Conclusion: Returning objects from functions is a powerful feature that improves flexibility and modularity
in Python programs.

Q18. Discuss the mutability property of objects in Python with suitable examples.

Introduction: Objects in Python may be mutable or immutable. Understanding mutability is important


because it determines whether an object's contents can be changed after creation.

Mutability: An object is said to be mutable if its contents can be modified after it is created. An object is
immutable if its contents cannot be modified after creation.

Examples

Mutable Objects

• Lists
• Dictionaries
• Sets
• Most class instances

Immutable Objects

• Integers
• Floats
• Strings
• Tuples

Example Program

class Student:

def __init__(self, name):


[Link] = name

s1 = Student("Rahul")

print("Before Modification:", [Link])

[Link] = "Anita"

print("After Modification :", [Link])

Output

Before Modification: Rahul


After Modification : Anita

Explanation

Step 1: An object s1 is created.


Step 2: The attribute name initially contains "Rahul".
Step 3: The value is changed.
[Link] = "Anita"
Step 4: The object reflects the new value.
Thus, objects of user-defined classes are mutable.

Advantages of Mutable Objects

1. Easy modification of data.


2. Efficient memory utilization.
3. Supports dynamic applications.

Conclusion: Most user-defined objects in Python are mutable, meaning their attributes can be modified
after creation.

Q19. What is meant by sameness of objects? Differentiate between equality and identity with examples.

Introduction: In Object-Oriented Programming, it is important to determine whether two objects contain


the same data or whether they actually refer to the same memory location.

Sameness of Objects: Sameness can be interpreted in two ways:


1. Equality
2. Identity

Equality

Two objects are equal if they contain the same values. Operator:

==

Identity

Two objects are identical if they refer to the same memory location. Operator:

is

Example Program

a = [1, 2, 3]
b = [1, 2, 3]
c=a
print(a == b)
print(a is b)
print(a is c)

Output

True
False
True

Explanation

Equality Check
a == b - Both lists contain the same values.
True - Thus the result is True
Identity Check
a is b - Different memory locations.
False - Thus the result is False
Same Object
a is c - Both refer to the same object.
True - Thus the result is True

Difference Between Equality and Identity

Equality (==) Identity (is)


Compares values Compares memory location
Checks contents Checks object reference
Returns True if values match Returns True if both names refer to same object
Conclusion: Equality checks object contents, whereas identity checks whether two references point to the
same object.

Q20. Explain copying of objects in Python. Differentiate between aliasing and copying with suitable
examples.

Introduction: When working with objects, multiple variables may refer to the same object or separate copies
of an object. This leads to the concepts of aliasing and copying.

Aliasing: Aliasing occurs when two variables refer to the same object. Example:

a = [10, 20, 30]


b=a - Both a and b refer to the same memory location.

Copying: Copying creates a new object with the same contents. Example:

a = [10, 20, 30]


b = [Link]() - Now a and b are different objects.

Example Program

a = [10, 20, 30]


b=a
c = [Link]()
[Link](40)

print("a =", a)
print("b =", b)
print("c =", c)

Output

a = [10, 20, 30, 40]


b = [10, 20, 30, 40]
c = [10, 20, 30]

Explanation

Aliasing
b=a - Both variables refer to the same object. Any change in a also affects b.
Copying
c = [Link]() - A separate object is created. Changes to a do not affect c.

Difference Between Aliasing and Copying

Aliasing Copying
Same object New object
Same memory location Different memory location
Aliasing Copying
Changes affect all aliases Changes do not affect copies
Memory efficient Requires additional memory
Advantages of Copying

1. Prevents unintended modifications.


2. Maintains data independence.
3. Useful in large applications.

Conclusion: Aliasing creates multiple references to the same object, whereas copying creates an
independent object with the same contents. Understanding this distinction is essential for managing mutable
objects correctly.

Q21. What is Inheritance? Explain its advantages with a suitable example.

Introduction: One of the most important features of Object-Oriented Programming (OOP) is Inheritance. It
allows a new class to acquire the properties and methods of an existing class. Inheritance promotes code
reusability and reduces duplication of code.

Definition of Inheritance: Inheritance is the mechanism by which one class acquires the attributes and
methods of another class.

• Parent Class (Base Class/Super Class): The class whose properties are inherited.
• Child Class (Derived Class/Sub Class): The class that inherits the properties.

General Syntax

class Parent:
pass

class Child(Parent):
pass

Advantages of Inheritance

1. Code reusability.
2. Reduces redundancy.
3. Improves maintainability.
4. Supports hierarchical classification.
5. Makes programs modular.

Example Program

class Person:

def __init__(self, name):


[Link] = name
def display(self):
print("Name:", [Link])

class Student(Person):
pass

s1 = Student("Rahul")

[Link]()

Output

Name: Rahul

Explanation

Step 1: Person class is defined.


class Person:
Step 2: Student inherits from Person.
class Student(Person):
Step 3: The object s1 automatically gets access to the inherited method.
[Link]()
Step 4: The inherited method displays the name.

Conclusion: Inheritance enables a class to acquire properties and methods from another class, promoting
code reuse and reducing duplication.

Q22. Write a Python program demonstrating Single Inheritance.

Introduction: Inheritance can be of several types. The simplest form is Single Inheritance, where one child
class inherits from one parent class.

Single Inheritance: When one derived class inherits from one base class, it is called Single Inheritance.

Diagram

Person
|
|
Student

Program

class Person:

def show(self):
print("I am a Person")

class Student(Person):

def study(self):
print("I am studying Python")

s = Student()

[Link]()
[Link]()

Output

I am a Person
I am studying Python

Explanation

Parent Class
class Person
Contains method show().
Child Class
class Student(Person)
Inherits show() and defines study().

Object Creation

s = Student() - The object can access both inherited and own methods.

Conclusion: Single inheritance allows a child class to reuse properties and methods of a single parent class.

Q23. Differentiate between Pure Functions and Modifiers with suitable examples.

Introduction: Functions in Python can either modify objects or leave them unchanged. Based on this
behavior, functions are classified as Pure Functions and Modifiers.

Pure Function: A Pure Function does not modify the object passed to it. Instead, it creates and returns a new
object.

Example

def add(a, b):


return a + b - The original values remain unchanged.

Modifier: A Modifier changes the object that is passed as an argument. Example


numbers = [10, 20, 30]

[Link](40)

The original list is modified.

Program

# Pure Function
def double(x):
return x * 2

a = 10

print(double(a))
print(a)

# Modifier
lst = [1, 2, 3]

[Link](4)

print(lst)

Output

20
10
[1, 2, 3, 4]

Difference Between Pure Functions and Modifiers

Pure Function Modifier


Does not modify original object Modifies original object
Returns a new value/object Changes existing object
Safer and predictable May cause side effects
Easier to debug Harder to debug
Conclusion: Pure functions preserve original data, whereas modifiers change the state of existing objects.

Q24. Explain the concept of Generalization in Object-Oriented Programming with an example.

Introduction: Generalization is a design principle in OOP used to identify common features among multiple
classes and place them in a common superclass.
Definition: Generalization is the process of extracting common properties and behaviors from multiple
classes and placing them into a more general parent class.

Example

Consider:
• Student
• Teacher
• Employee
All have:
• Name
• Age
These common features can be placed in a superclass called Person.

Diagram

Person

Student Teacher Employee

Program

class Person:

def __init__(self, name):


[Link] = name

class Student(Person):
pass

class Teacher(Person):
pass

Explanation

Common attribute:
[Link] - is generalized into class Person.

Advantages

1. Reduces duplication.
2. Simplifies design.
3. Improves maintainability.

Conclusion: Generalization identifies common features and places them in a superclass, improving software
design.
Q25. What is Operator Overloading? Illustrate Operator Overloading in Python with a suitable example.

Introduction: Operators such as +, -, *, and / are predefined in Python. Python allows these operators to
work with user-defined objects through Operator Overloading.

Definition: Operator Overloading is the process of giving additional meaning to existing operators when
applied to user-defined objects.

Need

Without operator overloading:

c = obj1 + obj2 - would generate an error.

With operator overloading, Python knows how to perform the operation.

Example Program

class Point:

def __init__(self, x):


self.x = x

def __add__(self, other):


return Point(self.x + other.x)

p1 = Point(10)

p2 = Point(20)

p3 = p1 + p2

print(p3.x)

Output

30

Explanation

Step 1
__add__() overloads the + operator.
Step 2
p1 + p2 - internally becomes
p1.__add__(p2)
Step 3: The result is a new object containing value 30.

Conclusion: Operator overloading allows operators to work with user-defined objects, making programs
more intuitive and readable.
Q26. Explain Polymorphism in Python with a suitable example.

Introduction: Polymorphism is one of the fundamental principles of OOP. It allows the same interface to be
used for different types of objects.

Definition: Polymorphism means "many forms." The same method name can behave differently depending
on the object calling it.

Example Program

class Dog:

def sound(self):
print("Dog Barks")

class Cat:

def sound(self):
print("Cat Meows")

animals = [Dog(), Cat()]

for a in animals:
[Link]()

Output

Dog Barks
Cat Meows

Explanation

Both classes contain:


sound()
But each class provides its own implementation. Thus, the same method call behaves differently.

Advantages

1. Flexibility.
2. Extensibility.
3. Code reuse.
4. Better software design.

Conclusion: Polymorphism allows a single interface to represent multiple forms, making programs flexible
and maintainable.
Q31. What are Exceptions? Explain Catching Exceptions and Raising User-Defined Exceptions with suitable
examples.

Introduction: During program execution, errors may occur due to invalid input, division by zero, file not
found, etc. Such runtime errors are called Exceptions.

Exception: An Exception is an abnormal event that interrupts the normal flow of program execution.
Examples:

• Division by zero
• Invalid input
• File not found

Catching Exceptions: Exceptions are handled using:

try
except

Example

try:
a = 10 / 0

except ZeroDivisionError:
print("Division by zero is not allowed")

Output

Division by zero is not allowed

Raising User-Defined Exceptions: Python allows programmers to generate exceptions using:

raise

Example

age = -5

if age < 0:
raise ValueError("Age cannot be negative")

Output

ValueError: Age cannot be negative

Complete Program

try:

num = int(input("Enter a number: "))

if num < 0:
raise ValueError("Negative numbers not allowed")

print("Number =", num)

except ValueError as e:

print("Error:", e)

Sample Output

Enter a number: -10


Error: Negative numbers not allowed

Advantages of Exception Handling

1. Prevents abrupt program termination.


2. Improves reliability.
3. Makes programs robust.
4. Handles unexpected situations gracefully.

Conclusion: Exceptions are runtime errors that can be handled using try-except blocks. User-defined
exceptions can be generated using the raise statement to enforce application-specific rules.

You might also like