PCEP Error Handling and Modules 2 — Questions and Answers
Question 1: What is the difference between a module and a script in Python?
- A module is imported for reuse; a script is executed directly (Correct answer)
- No difference
- Scripts cannot contain functions
- Modules cannot be run
Correct answer: A module is imported for reuse; a script is executed directly
Modules are designed for importing while scripts are designed for direct execution, though the same file can serve both purposes.
Question 2: How does Python determine the search path for modules?
- Through sys.path which includes current directory, PYTHONPATH, and installation directories (Correct answer)
- Only the current directory
- Only the installation directory
- Alphabetically by filename
Correct answer: Through sys.path which includes current directory, PYTHONPATH, and installation directories
Python searches multiple locations in order as defined in sys.path.
Question 3: What is the purpose of __name__ == "__main__" in Python?
- To run code only when the file is executed directly, not when imported (Correct answer)
- To name the program
- To create the main function
- To define the primary variable
Correct answer: To run code only when the file is executed directly, not when imported
This guard ensures code runs only during direct execution, not when the file is imported as a module.
Question 4: What are built-in exceptions in Python?
- Pre-defined exception classes like ValueError, TypeError, IndexError (Correct answer)
- User-created error messages
- Warning messages only
- Debugging tools
Correct answer: Pre-defined exception classes like ValueError, TypeError, IndexError
Python provides a hierarchy of built-in exception classes for common error types.
Question 5: How do you create a custom exception in Python?
- Define a class that inherits from Exception (Correct answer)
- Use a special keyword
- Modify built-in exceptions
- Custom exceptions are not possible
Correct answer: Define a class that inherits from Exception
Custom exceptions are created by defining a class that inherits from the Exception class or its subclasses.
Question 6: What is the purpose of the else clause in try-except?
- Runs only if no exception was raised in the try block (Correct answer)
- Runs only if an exception occurs
- Runs regardless of exceptions
- Replaces the except block
Correct answer: Runs only if no exception was raised in the try block
The else clause executes when the try block completes without raising any exceptions.
What is the difference between a module and a script in Python?