Gujarat Public School Computer Science Exam Key
Gujarat Public School Computer Science Exam Key
An exception in Python refers to an event that disrupts the normal flow of instructions during program execution. For example, a ZeroDivisionError occurs when a division by zero is attempted. Proper handling can be achieved using 'try-except', such as: ``` try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero") finally: print("This always executes") ``` In this scenario, the ZeroDivisionError is caught by the 'except' block, preventing the program from crashing and allowing a fallback message to be displayed, with 'finally' ensuring that the cleanup code runs regardless of the exception .
The 'pickle' module in Python is used for serializing and deserializing Python object structures, enabling saving Python objects into files and restoring them later. Serialization converts objects to a byte stream, suitable for writing to files, and deserialization reads the byte stream, reconstructing the original object. For example, to store a list of numbers, you can use: ``` import pickle numbers = [10,20,30,40,50] with open('numbers.dat','wb') as f: pickle.dump(numbers, f) with open('numbers.dat','rb') as f: nums = pickle.load(f) print(nums) ``` This code demonstrates writing a list to a file and reading it back, preserving the list structure .
The 'try-except-finally' construct is significant in Python for handling exceptions and ensuring that cleanup actions are performed regardless of an error occurrence. The 'try' block contains code that might cause an error, the 'except' block handles specific exceptions, and the 'finally' block contains code that will execute no matter the outcome, such as releasing resources. This ensures robust error management in code. For example, operations like file handling often use this construct to ensure files are closed properly even if an exception occurs .
A stack overflow occurs in data structures when a stack exceeds its capacity due to excessive 'PUSH' operations without adequate 'POP' operations to balance the addition of items. This results in an error due to lack of space to accommodate new elements. In contrast, regular stack operations like 'PUSH' simply add an item to the top of the stack, and 'POP' removes the top item and returns it. These operations are typically managed within the stack's size constraints, preventing overflow from occurring unless abused, as with continuous unchecked 'PUSH' actions . Stack overflow is more common in recursive programming due to excessive function calls without adequate base condition or termination control, unlike regular operations which are bounded by logical management .
In Python, the 'insert()' method allows inserting an element at a specified position in a list. It modifies the list in-place, adding the element without replacing other elements. For instance, using `L1.insert(2, 200)` on a list `L1` inserts 200 at index 2, shifting subsequent elements one position to the right . This method is particularly useful for precise placement of elements within a list, such as inserting new data into a sorted list while maintaining order or updating lists derived from input sequences .
Python implicitly converts data types during operations when it automatically handles type conversions to match the operation requirements, for example, converting integers to floats in arithmetic operations like '3 + 2.5', resulting in a float: 5.5 . In contrast, explicit type conversion requires the programmer to manually convert types using functions like int(), float(), or str(), such as converting a string '12' to an integer using 'int("12")'. Implicit conversion helps prevent some type errors by handling conversions smoothly, whereas explicit conversion offers greater control over the data types used in an operation .
In Python, function parameters are the variables listed in a function's definition that specify what kind of arguments it can accept. Arguments, on the other hand, are the actual values passed to a function when it is called . Python functions can indeed return multiple values by returning a tuple, which is accomplished using syntax like 'return a, b'. This allows for greater flexibility in functions, enabling them to output multiple results or values through tuple unpacking upon the function's completion .
'break' and 'continue' are control statements in Python loops, but they function differently. The 'break' statement terminates the current loop entirely, stopping further iterations and exiting the loop block. In contrast, the 'continue' statement skips the rest of the code inside the loop for the current iteration and proceeds to the next iteration. For example: ``` # Using break: for i in range(5): if i == 3: break print(i) # Output: 0 1 2 # Using continue: for i in range(5): if i == 3: continue print(i) # Output: 0 1 2 4 ``` In the 'break' example, the loop exits entirely when `i` equals 3. In the 'continue' example, the loop skips the print statement when `i` is 3, continuing with the next iteration .
'readlines()' and 'read()' are both file handling methods in Python, with distinct roles. 'readlines()' reads all lines in a file and returns them as a list, which is useful when you need to process lines individually or access the file content as a list . On the other hand, 'read()' reads the whole file into a single string, which can be beneficial when the entire content is required as a continuous block of text. The choice between the two depends on whether line-by-line processing is needed ('readlines()') or single-string processing suffices ('read()').
The 'w+' mode in the 'open()' function opens a file for both writing and reading. It signifies that the file is writable and readable, but it also truncates the file to zero length first, which deletes existing content . This mode can be useful in scenarios where it is necessary to rewrite the entire file content or when starting with a new file where both reading from and writing to the file will occur. Unlike 'r+' which allows reading and writing without truncating, or 'a+' which allows appending and reading without truncating, 'w+' is utilized when restarting content from scratch is required .