0% found this document useful (0 votes)
6 views7 pages

Python OOP Exercises and Exception Handling

The document outlines exercises related to classes and objects in Python, including creating a Bus class that inherits from a Vehicle class, implementing a BankAccount class, and handling exceptions. It emphasizes concepts like polymorphism, method overriding, and managing student records using file handling and exception handling. Additionally, it provides sample input/output scenarios for various programming tasks.

Uploaded by

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

Python OOP Exercises and Exception Handling

The document outlines exercises related to classes and objects in Python, including creating a Bus class that inherits from a Vehicle class, implementing a BankAccount class, and handling exceptions. It emphasizes concepts like polymorphism, method overriding, and managing student records using file handling and exception handling. Additionally, it provides sample input/output scenarios for various programming tasks.

Uploaded by

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

Exercises on Classes and Objects

1. Create a child class Bus that will


inherit all of the variables and methods
of the Vehicle class

2. Define a property that must have


the same value for every class instance
(object)
Define a class attribute”color” with a default value white. I.e.,
Every Vehicle should be white.
3. Create a Bus child class that inherits from the Vehicle class.
The default fare charge of any vehicle is seating capacity *
100. If Vehicle is Bus instance, we need to add an extra 10%
on full fare as a maintenance charge. So total fare for bus
instance will become the final amount = total fare + 10%
of the total fare.

Note: The bus seating capacity is 50. so the final fare amount
should be 5500. You need to override the fare() method of a
Vehicle class in Bus class.

Use the following code for your parent Vehicle class. We need
to access the parent class from inside a method of a child
class.
4) Create a class BankAccount with:

 Attributes: account_number, balance


 Methods:
o deposit(amount): Adds money to the account
o withdraw(amount): Deducts money if sufficient balance is available

Input:

Output:

5) Create a class Circle with a method area() that returns the area of the circle. Take the radius
as input while creating an object.
6) Create a parent class Vehicle with attributes brand and model. Create a child class Car that
inherits Vehicle and adds a new attribute seats. Create an object of Car and display all attributes.

7) Polymorphism with Method Overriding

Create a base class Shape with a method area(). Create two child classes Rectangle and Circle
that override the area() method.

Exception Handling

1) Write a Python program that takes two numbers as input and divides the first number by the
second. Handle the case where the second number is zero.

Sample Input / Output

2) Write a Python program that takes a number from the user and converts it to an integer.
Handle cases where the input is not a valid number.

Sample Input / Output


3) Write a Python program that attempts to open a file and reads its contents. Handle the case
where the file does not exist.
Sample Input / Output

4) Write a Python program that takes two numbers as input, performs division, and ensures
that a message is printed regardless of whether an exception occurs.

Sample Input / Output


Concept: Student Records Management Using File Handling
& Exception Handling

Key Features:

1. Uses a dictionary to store student records (Name -> Marks).


2. Reads and writes data from a plain text file ([Link]).
3. Uses exception handling for:
o Handling missing files (FileNotFoundError).
o Handling invalid inputs (ValueError).
o Ensuring smooth file operations.

Sample Input / Output


How This Works

1. load_data() → Reads data from [Link] and loads it into a dictionary.


2. save_data(data) → Writes dictionary data back into [Link] in Name:Marks
format.
3. Exception Handling:
o FileNotFoundError → If file is missing, it creates a new one.
o ValueError → Handles invalid inputs (e.g., non-numeric marks).
o try-except inside load_data() → Prevents crashing due to malformed file data.
4. User Menu:
o Allows adding, viewing, searching, updating, and deleting student records.

Common questions

Powered by AI

The document employs several strategies to ensure data integrity and error-free operations in the student records management system. These include using dictionaries to manage student records efficiently, implementing exception handling for common errors like FileNotFoundError and ValueError, and encapsulating file operations in robust methods like load_data() and save_data(). These mechanisms prevent data corruption, assist in smooth recovery from errors, and ensure that only valid entries are processed and stored in the student records .

Exception handling ensures that the student records management program continues to operate smoothly despite potential errors during file operations. The program manages specific exceptions such as FileNotFoundError by creating a new file if it is missing and ValueError by dealing with invalid inputs like non-numeric marks. Additionally, a try-except block inside load_data() is used to prevent crashes due to malformed file data, ensuring robustness in reading and writing operations .

Using dictionaries in conjunction with file handling to process student records enhances both efficiency and data management. Dictionaries provide fast lookups, additions, and updates of records due to their hash table implementation, allowing efficient management of student data. Meanwhile, file handling allows persistence of data, enabling records to be stored, retrieved, and updated across sessions. The combination ensures that the system maintains high performance while managing complex data operations seamlessly .

It is necessary for the Bus class to access the Vehicle class method to calculate the initial fare based on the seating capacity, which is a behavior inherited but needs to be extended in the Bus class. This can be achieved in Python using super() or explicitly naming the parent class while calling the method. The super() function allows calling the parent class method, facilitating the use of the base calculation before applying the additional maintenance charge specific to the Bus class .

Polymorphism is a concept in object-oriented programming that allows methods to be implemented in different ways depending on the object type. In the Shape class hierarchy, polymorphism is implemented through method overriding. The base class Shape defines a method area(), which is then overridden by the child classes Rectangle and Circle to provide specific implementations of calculating the area. This allows objects of Rectangle and Circle to call the area() method, which executes the overridden version specific to their class .

The Bus class illustrates inheritance by deriving from the Vehicle class, thereby acquiring all its variables and methods. This is demonstrated by the Bus class having a default fare calculation like any Vehicle. Method overriding is shown when the Bus class redefines the fare() method to add an extra 10% maintenance charge on top of the normal fare calculation, altering its behavior specifically for instances of Bus while keeping the original method signature .

To override methods in Python, the child class must define a method with the same name and parameters as the method it intends to override. In the context of the Bus and Vehicle classes, this involves defining a fare() method in the Bus class that calls the fare() method from the Vehicle class using a parent class function, then modifies the result by adding an additional 10% maintenance charge specific to buses. This effectively changes the behavior of the fare() method for Bus instances while keeping the same method signature .

Using a default value for class attributes, such as 'color' in the Vehicle class set to 'white', is beneficial because it ensures uniformity and reduces redundancy. It provides a consistent default state across all instances of the class, which simplifies code maintenance and increases readability. It is also useful for setting a standard behavior or attribute unless explicitly specified otherwise, enhancing the overall design by aligning class instances to a common theme or attribute without manual customization for every instance .

Encapsulation is demonstrated in the BankAccount class by defining attributes such as account_number and balance, which are kept private to protect the account’s internal state. Access to these attributes is controlled through methods like deposit() and withdraw(), which manage how values are added or deducted from the account based on specific conditions. This ensures that the internal state of the BankAccount is not directly manipulated, encapsulating the data within controlled interfaces .

Method overriding in object-oriented programming allows different shapes to have customized area calculations by redefining a common method in their respective classes. In the document, the base class Shape has an area() method that is overridden in each child class, such as Rectangle and Circle, to provide specific area computation logic depending on the shape's properties. This polymorphic behavior ensures that a call to area() results in executing the correct formula for the shape instance, promoting code reusability and flexibility in handling diverse data .

You might also like