Practice: Code Quality and Best Practices
Q1. Constant for tax
Define a constant TAX_RATE = 0.1 and print the tax on 200 (use TAX_RATE * 200).
Goal: Use named constants.
Q2. Add a docstring
Write a function cube(n) with a docstring "Return n cubed." and print cube.__doc__.
Goal: Write docstrings.
Q3. Type hinted function
Write greet(name: str) -> str that returns "Hello, " followed by the name. Print greet("Mia").
Goal: Add type hints.
Q4. Remove repetition
Write a function area(width, height) and use it to print the areas of 2x3 and 4x5 rectangles, each on its own line.
Goal: Apply DRY.
Q5. Safe default list
Write add_item(item, items=None) that creates a new list when items is None, appends the item and returns the list. Print add_item("a") and add_item("b").
Goal: Avoid mutable defaults.
Q6. Optional return type
Write first_even(numbers: list[int]) -> int | None returning the first even number or None. Print first_even([3, 5, 8, 10]) and first_even([1, 3]).
Goal: Use union type hints.
Q7. Shared default
What does this program print?
def add(x, box=[]):
box.append(x)
return box
add(1)
print(add(2))Goal: Predict the mutable default trap.
Q8. Docstring access
What does this program print?
def hi():
"""Say hi."""
return "hi"
print(hi.__doc__)Goal: Read __doc__.
Q9. enumerate
What does this program print?
for i, c in enumerate("abc"):
print(i, c)Goal: Use enumerate.
Q10. Hints are not enforced
What does this program print?
def double(n: int) -> int:
return n * 2
print(double("ab"))Goal: Know hints are not enforced.
Q11. None check
What does this program print?
value = None
if value is None:
print("missing")
else:
print("present")Goal: Compare with None properly.
Q12. Constant naming
What does this program print?
MAX_USERS = 3
users = ["a", "b", "c", "d"]
print(len(users) > MAX_USERS)Goal: Use constants in checks.
Q13. Fix the default list
This function keeps old data between calls. Fix it so that the two printed lists are [1] and [2].
def collect(x, bucket=[]):
bucket.append(x)
return bucket
print(collect(1))
print(collect(2))Goal: Fix a mutable default.
Q14. Fix shadowing
This code shadows the built-in sum and then fails. Rename the variable so that it prints 6.
sum = 0
for n in [1, 2, 3]:
sum += n
print(sum([1, 2, 3]))Goal: Avoid shadowing built-ins.
Q15. Fix the comparison
Fix the None comparison to follow good style and print yes.
value = None
if value == None:
print("yes")Goal: Use is None.
Q16. Good name
Why is days_left a better variable name than d?
Goal: Choose meaningful names.
Q17. Comment or docstring
When should you use a comment and when a docstring?
Goal: Differentiate comments and docstrings.
Q18. Refactor a price calculation
Write a function final_price(price, discount_percent=0, tax_percent=0) that applies the discount, then the tax. Print final_price(200, 10, 5).
Goal: Write clean functions.
Q19. Clean loop
Rewrite a loop so that it prints each name in ["Ann", "Bob"] in upper case using direct iteration (no range or index).
Goal: Write Pythonic loops.