When might you choose to raise an exception manually using raise?
raise
When you want to signal that an unexpected condition has occurred that your code cannot handle directly.
To automatically retry a failed operation without any intervention.
To replace all occurrences of built-in exceptions in your code.
To silently ignore errors and prevent the program from crashing.
Which code snippet correctly creates a dictionary where keys are numbers from 1 to 5 and values are their squares using a dictionary comprehension?
[num: num**2 for num in range(1, 6)]
(num: num**2 for num in range(1, 6))
{num: num**2 for num in range(1, 6)}
{num**2: num for num in range(1, 6)}
What does inheritance allow in object-oriented programming?
Creating objects of one class inside another class.
Restricting access to certain data and methods within a class.
Defining methods with the same name but different implementations in different classes.
Creating new classes that inherit properties and methods from existing classes.
Which string method is used to determine if a string ends with a specified suffix?
startswith()
index()
find()
endswith()
What is the output of the following Python code?
with open('data.txt', 'w') as file: file.write('Hello, world!') print(file.read())
Hello, world!
The code will raise a ValueError.
The code will print nothing.
The code will raise an IOError.
What is the primary advantage of using the with statement for file operations in Python?
with
It automatically closes the file, even if exceptions occur.
It improves code readability.
It provides better performance for large files.
All of the above.
Which regular expression will match any string that starts with 'a' and ends with 'z'?
'^a.+z$'
'^a.*z$'
'a.+z'
'a.*z'
What is the output of the following Python code:
string = 'Hello, world!' print(string.replace('o', '0', 1))
Error
Hell0, w0rld!
Hell0, world!
What is a key difference between instance methods and class methods in Python?
Instance methods are defined using the 'classmethod' decorator, while class methods use the 'staticmethod' decorator.
Class methods can access instance variables, while instance methods cannot access class variables.
There is no practical difference; both can be used interchangeably.
Instance methods operate on specific instances of a class, while class methods operate on the class itself.
What differentiates a deque from a regular Python list?
deque
Deques are immutable, while lists are mutable.
Deques can only store integers, while lists can store any data type.
Deques are thread-safe, while lists are not.
Deques are optimized for appending and popping elements from both ends, while lists are optimized for operations at the end.