Modern Idioms — Walrus, Unpacking, Enumerate Patterns & EAFP — Concept Check
Questions on Modern Idioms — Walrus, Unpacking, Enumerate Patterns & EAFP. The idioms that mark current Python: the walrus operator :=, star-unpacking, dict merging with |, f-string debugging, and choosing EAFP over permission-checking.
Questions in this quiz
6 questions on Modern Idioms — Walrus, Unpacking, Enumerate Patterns & EAFP — Concept Check. Work through them here, then start the quiz to answer them and see your score.
1.In a Python script, you need to read chunks from a file and process them until the file ends. Which approach uses modern idioms effectively?
- AUse a while loop with the walrus operator to read and process in one step.
- BUse a for loop with a break statement to stop when the file ends.
- CUse recursion to read and process until the file ends.
- DUse a while loop with a separate read and process step.
2.You have a dictionary `base` and want to update it with another dictionary `override`. Which method is preferred in Python 3.9+?
- AUse a loop to manually update `base` with `override` values.
- BUse `base + override` to concatenate the dictionaries.
- CUse `base.update(override)` to merge the dictionaries.
- DUse `base | override` to merge the dictionaries, with `override` values taking precedence.
3.A developer uses `if m := re.search(r'\d+', line)` in their code. What is the benefit of this approach?
- AIt improves performance by caching the search result.
- BIt allows multiple regex patterns to be tested simultaneously.
- CIt assigns and tests the match object in a single expression.
- DIt automatically converts the match object to a string.
4.A developer uses `print(f'{total=} {count=} {total/count=:.1f}')` for debugging. What is the advantage of this approach?
- AIt executes faster than traditional print statements.
- BIt requires less memory by not storing variable names.
- CIt formats and labels the variables, making the output more readable.
- DIt automatically logs the output to a file for later review.
5.In a Python script, you need to count word occurrences in a sentence. Which idiom is most efficient?
- AUse a dictionary with `get` method for default values.
- BUse a set to track unique words and count separately.
- CUse a list to count occurrences and convert to a dictionary.
- DUse a nested loop to count each word individually.
6.A developer is using `base | override` to merge two dictionaries. What should they be aware of?
- AThe `override` dictionary will be modified in place.
- BThe rightmost dictionary's values will take precedence.
- CThe `base` dictionary will be modified in place.
- DThe operation will throw an error if keys overlap.