Class 12 Python Stack & Exception Programs
Class 12 Python Stack & Exception Programs
Using a 'finally' block is necessary in scenarios where critical cleanup actions must be performed, such as closing a database connection or file, regardless of whether an exception is thrown or caught. For instance, when performing file operations, it is crucial to ensure the file is closed after operations, which can be reliably done using finally: try: file = open('file.txt', 'r') # perform operations finally: file.close() even if exceptions are managed in the except block .
To count even numbers in a stack, iterate over the stack using a for loop and use the modulus operator to check if each element is divisible by two (e.g., if element % 2 == 0). Increment a counter for each even number found. This ensures all elements are evaluated without altering the stack .
To implement a stack using a list in Python, you can define a list and use append() to push elements onto the stack and pop() to remove the top element. The append() function adds an element to the end of the list, simulating the 'push' operation, while pop() removes the last element, simulating the 'pop' operation. These operations maintain the Last In, First Out (LIFO) property of stacks .
To reverse the contents of a stack in Python, you can use the list's slicing feature. By assigning stack[::-1] to stack, you create a new list with elements in reverse order. Alternatively, repeatedly pop elements from the original stack and push them onto a new stack, replicating the reversal manually. Both methods maintain the stack properties .
To display all elements of a stack without removing them, iterate over the stack list and print each element. It's important to avoid using any operations that could modify the stack's contents, such as pop(). The operation should be purely read-only to maintain the stack's state .
To handle a situation where a file doesn't exist in Python, encapsulate the file reading code in a try-except block. Use the FileNotFoundError exception to catch and handle this specific error by displaying a meaningful message to the user. For example: try: with open('file.txt', 'r') as f: content = f.read() except FileNotFoundError: print('File does not exist').
To search for an element in a stack implemented using a list, use a linear search to iterate through each element of the list. This can be achieved with a for loop checking each element against the target value. The limitation is that this operation has a time complexity of O(n), meaning it requires inspecting each element, which is not efficient for large stacks .
To handle multiple exceptions like ValueError and ZeroDivisionError in Python, use separate except blocks for each exception after the try block. This allows you to define specific handling logic for each exception type. For example: try: result = int(num1) / int(num2) except ValueError: print('Invalid number entered') except ZeroDivisionError: print('Cannot divide by zero').
A 'try-finally' block in Python ensures that some code is executed no matter what, even if an exception is raised in the try block. The finally block always executes after the try block, which can be useful for code that needs to run regardless of whether an exception occurs, such as closing files or releasing resources. This characteristic makes it reliable for cleanup activities .
To handle a ZeroDivisionError in Python, you can use a try-except block. You place the code that might raise the ZeroDivisionError in the try block. In the except block, you catch the ZeroDivisionError and provide a way to handle it, such as printing an error message. For instance: try: result = num1 / num2 except ZeroDivisionError: print('Cannot divide by zero').