0% found this document useful (0 votes)
9 views2 pages

Python Programming Assignment 3 Tasks

Uploaded by

amnakhalidgsr
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)
9 views2 pages

Python Programming Assignment 3 Tasks

Uploaded by

amnakhalidgsr
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

Python Programming - Assignment 3

Questions:
1. Write a Python program to create a text file named '[Link]' and write 5 student
names into it.

2. Write a program to read and display the contents of '[Link]'.

3. Write a program that appends 3 more student names to '[Link]'.

4. Write a program that counts the total number of lines in '[Link]'.

5. Write a program to handle the error when trying to read a file that does not exist.

6. Write a program that asks the user to enter a number and handles the error if the user
enters text instead.

7. Write a program to divide two numbers entered by the user and handle the error if the
denominator is zero.

8. Write a program that asks the user to input a filename. Handle the error if the file cannot
be opened.

9. Define a class called 'Book' with attributes title and author. Create an object and display
its details.

10. Add a method in the 'Book' class that displays a message like 'The book title is XYZ by
Author ABC'.

11. Create a class 'Student' with attributes name and age. Write a method to display student
details.

12. Write a program where the 'Student' class constructor (__init__) takes name and age as
arguments and initializes them.

13. Create a class 'Calculator' with methods add, subtract, multiply, and divide. Demonstrate
its usage.

14. Create a class 'Teacher' that inherits from 'Person' class and adds subject as a new
attribute.

15. Write a program to demonstrate method overriding. (Example: a parent class Animal
with method sound(), and a child class Dog that overrides sound()).

16. Write a program to read a file and handle any error that might occur during reading (e.g.,
FileNotFoundError, PermissionError).
17. Create a class 'Library' with methods to add books, remove books, and display all books.
Handle the error if a user tries to remove a book not in the library.

18. Write a program that takes user input for numbers and stores them in a file. Then read
the file and display the sum of the numbers.

19. Write a program that writes 10 random numbers into a file and then finds the largest
number from the file.

20. Create a class 'Employee' with attributes name and salary. Write a method to give a
bonus and update the salary.

21. Write a program to handle multiple exceptions (e.g., ZeroDivisionError, ValueError) in a


single block.

22. Create a class 'Course' with attributes course_name and duration. Write a method to
display the details.

23. Write a program that counts the number of words in a given text file.

Common questions

Powered by AI

Exception handling is critical in file operations to prevent program crashes and maintain data integrity. For instance, attempting to open a non-existent file raises a FileNotFoundError, which can be handled using a try-except block to inform the user without crashing the program: ```python try: with open('file.txt', 'r') as file: content = file.read() except FileNotFoundError: print('File not found.') ``` Similarly, attempting to read a file without the necessary permissions raises a PermissionError, which should also be managed to maintain program functionality. Handling such exceptions allows programs to provide informative messages and potentially alternative solutions, like retrying with a different file or permissions . This not only improves robustness but also enhances user trust and data safety as unexpected exceptions are caught and addressed properly.

Method overriding in Python allows a subclass to provide a specific implementation of a method already defined in its superclass. This is particularly useful in situations where we need the subclass to exhibit behavior that is different from its superclass. For example, in the case of a parent class 'Animal' with a method 'make_sound()', you can override this in a subclass 'Dog' to provide a specific sound, such as 'bark()' . The benefits of this approach include enhanced flexibility and reusability, as it allows for creating more specific behaviors without altering the existing parent class code. It also supports polymorphism, enabling an object to be treated as an instance of its parent class, simplifying code maintenance and expansion .

Encapsulation in Python is implemented by using private and protected attributes and methods, which are not directly accessible from outside the class, safeguarding the internal representation of an object. Attributes can be made private by prefixing them with double underscores (e.g., `__private_attr`), while single underscores indicate protected attributes intended for subclass use. ```python class Example: def __init__(self, value): self.__private_value = value def get_value(self): return self.__private_value ``` The primary benefit of encapsulation is to restrict direct access to some of an object's components, which can reduce the risk of unintended interference and improve modularity by separating concerns. It allows internal state changes through controlled interfaces, promoting data integrity and security . Additionally, it enhances code maintainability by providing clear boundaries within which the internal logic can evolve independently of external code.

Method overriding occurs when a subclass provides a specific implementation of a method already defined in its superclass, allowing for tailored behaviors. In practical terms, consider a `Animal` class with a `sound()` method, and a `Dog` subclass that overrides this method: ```python class Animal: def sound(self): print('Some generic animal sound') class Dog(Animal): def sound(self): print('Bark') ``` In this example, the `sound()` method in `Dog` overrides the `sound()` method in `Animal`, so for a `Dog` instance, calling `sound()` will output 'Bark'. This allows for polymorphism, where a subclass can be treated as an instance of its parent, yet exhibit subclass-specific behavior . Overriding promotes flexibility and scalability in software design, allowing extensions and modifications without altering existing code.

Modeling entities like 'Book' or 'Student' using a class in Python offers several advantages over using dictionaries. First, classes enable encapsulation, allowing data (attributes) and functions (methods) to be packed together, which helps in organizing related data and behavior. Second, classes support inheritance and polymorphism, making it easy to extend and modify functionality without altering existing code. For instance, you can create a subclass that overrides or extends methods from the parent class . Third, classes provide data hiding through private variables and methods, which are inaccessible from outside the class, thus protecting the integrity of the data . Finally, classes make the code more readable and maintainable by defining clear interfaces and fostering reusability through well-defined methods and attributes .

Input validation improves the robustness of a Python program by ensuring that data entered by a user meets the expected form and constraints before being processed, thus preventing runtime errors and unintended behavior. Strategies for input validation include: 1. Using conditional statements to check if input meets certain criteria, such as type or value range: ```python user_input = input('Enter a number between 1 and 10: ') try: number = int(user_input) if not 1 <= number <= 10: raise ValueError('Number not within range') except ValueError as e: print(f'Invalid input: {e}') ``` 2. Employing regular expressions to ensure format compliance, such as email or phone number verification. 3. Utilizing try-except blocks to handle improper types, catch exceptions like ValueError when converting input, and guide users towards correction. These strategies enhance software reliability by preempting errors before they manifest, leading to a more predictable and user-friendly experience . They also protect systems from potentially malicious input, contributing to application security.

Effective management of user input errors in Python, especially in numerical operations, involves validation and handling exceptions. For example, when a program requires a number input, you can use a try-except block to catch a ValueError if the user enters non-numeric data: ```python try: number = int(input('Enter a number: ')) except ValueError: print('Invalid input: Please enter a valid number.') ``` Additionally, when performing divisions, you should handle a ZeroDivisionError using a try-except block, ensuring the program remains stable even when dividing by zero: ```python try: result = numerator / denominator except ZeroDivisionError: print('Cannot divide by zero.') ``` By incorporating these practices, the program avoids crashes and can guide the user towards valid input, enhancing user experience .

In Python, inheritance allows a class to inherit attributes and methods from another class, facilitating code reuse and a hierarchical class structure. For example, consider a base class 'Person' with attributes 'name' and 'age'. You can create a subclass 'Teacher' that inherits from 'Person' and adds a new attribute, 'subject'. ```python class Person: def __init__(self, name, age): self.name = name self.age = age class Teacher(Person): def __init__(self, name, age, subject): super().__init__(name, age) # Calls the initializer of the parent class self.subject = subject ``` The `Teacher` class utilizes inheritance by using `super()` to call the parent class constructor, thus integrating the base attributes while extending with `subject` specific to teachers. This showcases efficient structuring of related class data with minimal redundancy .

To develop a Python class for managing a library of books with error handling, follow these steps: 1. Define a class 'Library' with an attribute to store a list of books, for example, `self.books = []`. 2. Implement methods to add, remove, and display books. In the `add_book` method, append a book to `self.books`. 3. For `remove_book`, check if the book exists in `self.books` before attempting removal. Use a try-except block to handle errors and provide feedback if the book is not found: ```python def remove_book(self, book_title): try: self.books.remove(book_title) except ValueError: print('Book not found in the library.') ``` 4. In `display_books`, print the list of books or state that the library is empty if no books are present. 5. Consider adding a method to search for a book, with error handling for an empty library. 6. Test the class with various scenarios to ensure robust error handling .

To handle errors when attempting to read a non-existent file in Python, you can use a try-except block to catch the FileNotFoundError exception. This is important because it allows the program to fail gracefully and provide meaningful feedback to the user instead of crashing. Here is a basic way to handle this exception: ```python try: with open('non_existent_file.txt', 'r') as file: content = file.read() except FileNotFoundError: print('The file does not exist.') ``` By handling such exceptions, the program can continue executing subsequent code or offer the user options to resolve the error, such as creating the file or trying a different file name .

You might also like