Python Programming Question Bank
Python Programming Question Bank
In Python, string concatenation can be performed using the '+' operator, which merges strings together but creates a new string object, impacting performance due to increased memory usage with large strings or repeated concatenations within loops . Alternatively, using ''.join()' is more efficient for concatenating multiple strings, like in a list, as it processes them in a single pass . String replication with '*' allows a string to be repeated a specified number of times, creating a new string each time, which can affect performance with very large results or excessive repetitions. Both methods affect readability, where '+' is intuitive for simple operations, while ''.join()' enhances readability in more complex scenarios like joining list elements . Each approach requires balancing simplicity against efficiency depending on context and frequency of operation use .
Mutable types, such as lists, allow modifications after their creation, which means elements can be added, removed, or changed without creating a new object . Conversely, immutable types, such as tuples, do not allow changes once created; instead, any 'change' creates a new object entirely . This difference affects memory usage and performance. For example, using a list for data that frequently changes can be more efficient due to their ability to change in place, whereas using a tuple can be more appropriate for fixed collections of items. The choice between mutable and immutable types also impacts how functions handle these objects, as immutable objects are safer from inadvertent modification when passed as arguments .
The 'shutil' module in Python provides several high-level file and directory handling functions that simplify tasks such as copying and deleting files . The 'shutil.copytree()' function can recursively copy a directory tree, preserving metadata, while 'shutil.move()' can move a file or directory to another location . For deleting files or directories, 'shutil.rmtree()' can remove an entire directory tree. These functions abstract away the complexity of file manipulation, allowing developers to handle files with simple commands . Using 'shutil.copyfile()', for instance, makes it straightforward to copy files, improving code readability and reducing error-prone code .
Comparison operators evaluate the values to determine their relation, while Boolean operators such as 'and', 'or', and 'not' evaluate the truth value of expressions . The given expression '2+2==4 and not 2+2 == 5 and 2*2 == 2+2' checks multiple conditions: '2+2==4' is True, and 'not 2+2==5' negates the Falsehood of '2+2==5', resulting in True. The '2*2==2+2' checks if both sides of the multiplication and addition yield the same result, which is True. Since all sub-expressions are true, the whole expression evaluates to True .
The 'prototype & patch' development process involves creating a basic, working model of a program quickly ('prototype'), then iteratively refining and enhancing it ('patching' phase). This method emphasizes quick iteration and gradual feature incorporation, reducing complexity by focusing on incremental improvements. It facilitates user feedback early in the process and allows developers to address issues incrementally, improving code quality over time . For example, building a simple web scraper with no error handling as a prototype, then iteratively adding features like timeout handling, logging, and data caching during the patching phase, illustrates this concept. It enhances coding by balancing creativity with stability, leading to robust applications adaptable to new requirements .
In Python, the local scope refers to the variables defined within a function, accessible only within that function's context. The global scope involves variables defined outside functions, accessible throughout the entire program. Python resolves the variable names by checking local scopes first, then outer scopes, and finally global scopes if no local match is found . For example, consider a function that modifies a global variable: ```x = 5 def change_var(): global x x = 10 change_var() print(x)``` Initially, 'x' is 5 globally, but 'change_var()' updates 'x' to 10 using the 'global' keyword, reflecting this change outside the function .
Using 'sys.exit()' allows for immediate program termination, which can be useful when ending a program if a critical error occurs or after successfully completing all tasks . It makes the code's intent explicit where and why the program stops, aiding in debugging and readability. However, using 'sys.exit()' carries drawbacks, such as abruptly halting the program without releasing resources properly or performing necessary clean-up tasks. It can bypass exception handling and can stop a program's usual flow control, potentially causing loss of data or incomplete processing of information . Therefore, careful consideration is needed when integrating 'sys.exit()' in larger codebases. Additionally, using exceptions for error handling may offer more controlled termination while providing feedback to the program or user .
Python handles exceptions using try-except blocks, which encapsulate potentially error-generating code, allowing the program to continue execution or handle the error gracefully . The 'try' section contains code that may throw an exception, while 'except' blocks specify how to respond to particular exceptions. Python also provides 'finally' blocks, which execute code regardless of whether an exception was raised, and 'else' blocks, for code that executes only if no exception occurs. This robust structure prevents unexpected termination, allowing informative error handling and clean resource management . For example: ```try: x = 1/0 except ZeroDivisionError: print("Cannot divide by zero")``` This code catches the ZeroDivisionError, preventing a crash and allowing for a user-friendly error message .
The 'logging' module in Python provides a flexible framework for emitting log messages from Python programs, crucial for tracking code execution and identifying issues . It helps maintain code without extensively using 'print()' statements, allowing developers to categorize issues by severity and maintain a timestamped record of program execution . Its logging levels are: 'DEBUG', 'INFO', 'WARNING', 'ERROR', and 'CRITICAL', which help prioritize messages for normal information, debugging purposes, warnings, errors, and serious failures, respectively . Logging facilitates debugging by capturing detailed execution traces and enables developers to monitor applications at various granularity levels, enhancing maintainability by adjusting the level of detail in logs without changing code structure extensively .
The 'zipfile' module provides tools for creating, reading, and extracting ZIP files in Python, allowing efficient file handling and compression . To create a ZIP file, 'ZipFile()' is used along with 'write()', which adds files to the archive: ```import zipfile with zipfile.ZipFile('example.zip', 'w') as zf: zf.write('file.txt', compress_type=zipfile.ZIP_DEFLATED)``` Reading ZIP files uses 'ZipFile()' with 'r' mode: ```with zipfile.ZipFile('example.zip', 'r') as zf: print(zf.namelist())``` Extraction is managed by 'extract()' or 'extractall()', which retrieve files back from the archive: ```with zipfile.ZipFile('example.zip') as zf: zf.extract('file.txt', 'extracted/')``` These functions enhance file manipulation capabilities by enabling efficient storage, transmission, and handling of multiple files as a single archive, improving performance and organization .