livepython.net
CHAPTER 16Styling Your Code (PEP 8)
16.5  PRACTICE

Python PEP 8 Practice Questions for Beginners

Chapter 16 Recap and Practice

Your code now looks like the code of a real Python programmer. Here is the chapter in one table:

You writeIt means
PEP 8Python's style guide: how code looks, not what it does
total_price, get_total()variables and functions in snake_case; functions start with a verb
MAX_LIVES = 3a constant in UPPER_CASE, at the top of the program
BankAccounta class in PascalCase (chapter 20)
full_marks, not maxnever reuse a built-in function's name
4 spacesone indentation level; never tabs, never mixed
total = price * qtyone space around operators and after commas
print(a, b, sep="-")no spaces around = in a keyword argument or default value
two blank linesbefore and after every top-level function
79 charactersthe longest a line should be; break long lines inside brackets
one statement per lineno semicolons, every block on its own lines
TAX_RATE = 0.18a named constant instead of a magic number
one job per functionif you copy code, make a function
# why, not whatcomments explain the reason, two spaces after the code
no dead codedelete commented-out lines, debug prints and code after return

And remember: Python checks only a few of these rules. The rest is up to you, so read your code once more before you call it finished.

Practice questions

Most of these questions give you a messy program that already works, or almost works. Your job is to make it clean. The tests check only the output, so they can't see your style: check each rule in the question yourself. Use input() with no prompt text.

PEP 8 and why style matters

  1. 140.Python Program to Rewrite Squashed Code in PEP 8 StyleEasySolve
  2. 141.Fix a Messy Python Program That Won't RunMediumSolve

Naming conventions

  1. 142.Python Program to Rename Unclear VariablesEasySolve
  2. 143.Fix a Variable That Hides a Python Built-in FunctionEasySolve
  3. 144.Python Program to Rename Functions and Constants in PEP 8 StyleMediumSolve

Indentation, spacing and line length

  1. 145.Fix the Indentation in a Python FunctionEasySolve
  2. 146.Python Program to Break a Long Line of Code (PEP 8)MediumSolve

Clean code habits

  1. 147.Python Program to Replace Magic Numbers with Named ConstantsEasySolve
  2. 148.Python Program to Replace Repeated Code with a FunctionMediumSolve
  3. 149.Python Program to Clean Up a Messy Report CardHardSolve

Clean code is code someone else can read. Next, you'll learn to handle errors while your program runs: exceptions.