Python Programming Sample Answers
Python Programming Sample Answers
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.
Example
Consider a Student.
Attributes:
• Name
• USN
• Marks
Methods:
• Study
• Attend Class
• Display Details
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.
It specifies:
Syntax
class ClassName:
pass
Example
class Student:
pass
Object: An Object is an instance of a class. Objects occupy memory and store actual values.
Syntax
object_name = ClassName()
Example
s1 = Student()
Example Program
class Student:
def display(self):
print("Name :", [Link])
print("USN :", [Link])
s1 = Student("Rahul", "2HB26CS001")
[Link]()
Output
Name : Rahul
USN : 2HB26CS001
Explanation
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
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.
Example Program
class Car:
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.
1. Memory is allocated.
2. The constructor (__init__()) is called automatically.
3. Attributes are initialized.
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
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__()
Syntax
Example Program
class Book:
def display(self):
print("Title :", [Link])
print("Author:", [Link])
[Link]()
Output
Explanation
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:
• Name
• USN
• Marks
Types of Attributes
class Student:
s1 = Student("Rahul", 85)
s2 = Student("Anita", 92)
print([Link], [Link])
print([Link], [Link])
Output
Rahul 85
Anita 92
Explanation
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.
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:
Modifying Attributes: The value of an attribute can be changed after object creation.
Example:
Example Program
class Student:
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.
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 display(self):
print("USN :", [Link])
print("Name :", [Link])
print("Marks :", [Link])
Output
USN : 2HB26CS001
Name : Rahul
Marks : 85
Explanation
Applications
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.
Syntax
class ClassName:
def method_name(self):
1. Perform tasks.
2. Manipulate data.
3. Encapsulate functionality.
4. Improve code organization.
Example Program
class Calculator:
calc = Calculator()
Output
Sum = 30
Explanation
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:
s1
s2
s3
Python must know which object's attributes are being accessed. The self parameter provides this
information.
Example Program
class Student:
def display(self):
print("Name :", [Link])
s1 = Student("Rahul")
[Link]()
Output
Name : Rahul
Explanation
Constructor
Method
Internal Working
Advantages of self
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:
calc = Calculator()
Output
Addition = 30
Subtraction = 10
Explanation
[Link](20,10)
Advantages
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)
[Link]
Example Program
class Student:
s1 = Student("Rahul", 85)
display(s1)
Output
Explanation
Advantages
Conclusion: Objects can be passed as arguments to functions in Python, allowing functions to access and
manipulate object data effectively.
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 distance(point):
d = (point.x**2 + point.y**2)**0.5
return d
p1 = Point(3, 4)
Output
Distance = 5.0
Explanation
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.
class Employee:
def process(emp):
annual_salary = [Link] * 12
e1 = Employee("Ravi", 50000)
process(e1)
Output
Explanation
Advantages
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:
object_name.__str__()
Purpose of __str__()
Example Program
class Student:
def __str__(self):
return "Name: " + [Link] + ", Marks: " + str([Link])
s1 = Student("Anita", 92)
print(s1)
Output
Explanation
Name: Anita, Marks: 92 - The method converts object data into a readable string.
Advantages
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
Example Program
class Book:
def __str__(self):
return "Book: " + [Link] + \
", Author: " + [Link]
print(b1)
Output
Explanation
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.
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
Example Program
class Point:
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
Advantages
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 create_student():
s = Student("Rahul")
return s
s1 = create_student()
print("Student Name:", [Link])
Output
Explanation
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.
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:
s1 = Student("Rahul")
[Link] = "Anita"
Output
Explanation
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.
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
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:
Copying: Copying creates a new object with the same contents. Example:
Example Program
print("a =", a)
print("b =", b)
print("c =", c)
Output
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.
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
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.
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:
class Student(Person):
pass
s1 = Student("Rahul")
[Link]()
Output
Name: Rahul
Explanation
Conclusion: Inheritance enables a class to acquire properties and methods from another class, promoting
code reuse and reducing duplication.
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
[Link](40)
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]
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
Program
class Person:
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
Example Program
class Point:
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")
for a in animals:
[Link]()
Output
Dog Barks
Cat Meows
Explanation
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
try
except
Example
try:
a = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed")
Output
raise
Example
age = -5
if age < 0:
raise ValueError("Age cannot be negative")
Output
Complete Program
try:
if num < 0:
raise ValueError("Negative numbers not allowed")
except ValueError as e:
print("Error:", e)
Sample Output
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.