Practice: Code Quality and Best Practices

« Read the chapter

Q1. Constant for tax

BeginnerCoding

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

BeginnerCoding

Write a function cube(n) with a docstring "Return n cubed." and print cube.__doc__.

Goal: Write docstrings.

Q3. Type hinted function

BeginnerCoding

Write greet(name: str) -> str that returns "Hello, " followed by the name. Print greet("Mia").

Goal: Add type hints.

Q4. Remove repetition

IntermediateCoding

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

IntermediateCoding

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

AdvancedCoding

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

AdvancedOutput

What does this program print?

Code
def add(x, box=[]):
    box.append(x)
    return box

add(1)
print(add(2))

Goal: Predict the mutable default trap.

Q8. Docstring access

BeginnerOutput

What does this program print?

Code
def hi():
    """Say hi."""
    return "hi"

print(hi.__doc__)

Goal: Read __doc__.

Q9. enumerate

BeginnerOutput

What does this program print?

Code
for i, c in enumerate("abc"):
    print(i, c)

Goal: Use enumerate.

Q10. Hints are not enforced

IntermediateOutput

What does this program print?

Code
def double(n: int) -> int:
    return n * 2

print(double("ab"))

Goal: Know hints are not enforced.

Q11. None check

IntermediateOutput

What does this program print?

Code
value = None
if value is None:
    print("missing")
else:
    print("present")

Goal: Compare with None properly.

Q12. Constant naming

BeginnerOutput

What does this program print?

Code
MAX_USERS = 3
users = ["a", "b", "c", "d"]
print(len(users) > MAX_USERS)

Goal: Use constants in checks.

Q13. Fix the default list

IntermediateDebugging

This function keeps old data between calls. Fix it so that the two printed lists are [1] and [2].

Code
def collect(x, bucket=[]):
    bucket.append(x)
    return bucket

print(collect(1))
print(collect(2))

Goal: Fix a mutable default.

Q14. Fix shadowing

IntermediateDebugging

This code shadows the built-in sum and then fails. Rename the variable so that it prints 6.

Code
sum = 0
for n in [1, 2, 3]:
    sum += n
print(sum([1, 2, 3]))

Goal: Avoid shadowing built-ins.

Q15. Fix the comparison

BeginnerDebugging

Fix the None comparison to follow good style and print yes.

Code
value = None
if value == None:
    print("yes")

Goal: Use is None.

Q16. Good name

BeginnerConceptual

Why is days_left a better variable name than d?

Goal: Choose meaningful names.

Q17. Comment or docstring

IntermediateConceptual

When should you use a comment and when a docstring?

Goal: Differentiate comments and docstrings.

Q18. Refactor a price calculation

AdvancedApplication

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

BeginnerApplication

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.