PCPP 32 10x PCPP Certified Professional Python Programmer 1 · Free Practice Question Hard
Question 19
The Zen of Python says "Beautiful is better than ugly."
With that in mind, which code best fits that sentence?
-
A
- from pathlib import Path
- import zipfile
- path = Path.cwd().joinpath('cars.csv')
- with zipfile.ZipFile('archive.zip', 'w') as zip:
- zip.write(path, path.name, compress_type=zipfile.ZIP_DEFLATED)
-
B
- from pathlib import Path
- import zipfile
- path = Path.cwd().joinpath('cars.csv')
- with zipfile.ZipFile('archive.zip', 'w') as zip:
- zip.write(path, path.name, compress_type=zipfile.ZIP_DEFLATED)
-
C
- from functools import partial
- def fv(rate, m, n, pv):
- return pv * (1 + (rate / m)) ** (n * m)
- annual_acc_factor = partial(fv, n=1, pv=1)
- print(annual_acc_factor(0.04, 1))
- print(annual_acc_factor(0.04, 4))
- print(annual_acc_factor(0.06, 12))
-
D
- from urllib.request import urlopen
- with urlopen('http://python.org') as response:
- html = response.read().decode('utf-8')
- lines = [line.strip() for line in html.splitlines() if line][:5]
- for line in lines:
- print(line)
Reveal correct answer
Correct answer: A
A.
This code is clean and readable. It uses pathlib for path manipulations, which is more modern and expressive compared to older methods. The zipfile operations are also clear and concise. The overall structure of the code is simple and aligns well with the Zen of Python by being clear and straightforward.
B.
This option is almost identical to the correct option, but it has a trailing space at the end of the with statement's block. Although this doesn't impact functionality, it slightly affects the code’s readability and cleanliness.
C.
This code demonstrates the use of functools.partial to simplify function calls. While it is clean and functional, it is more complex than necessary for a simple demonstration, which may detract from its elegance compared to the straightforward approach in the correct option.
D.
This code is functional and does the job, but it is less directly related to the principle of "beautiful" code because it involves multiple steps that are less straightforward and can be seen as more complex compared to the simple operations in the correct option.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
