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 write | It means |
|---|---|
| PEP 8 | Python'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 = 3 | a constant in UPPER_CASE, at the top of the program |
BankAccount | a class in PascalCase (chapter 20) |
full_marks, not max | never reuse a built-in function's name |
| 4 spaces | one indentation level; never tabs, never mixed |
total = price * qty | one space around operators and after commas |
print(a, b, sep="-") | no spaces around = in a keyword argument or default value |
| two blank lines | before and after every top-level function |
| 79 characters | the longest a line should be; break long lines inside brackets |
| one statement per line | no semicolons, every block on its own lines |
TAX_RATE = 0.18 | a named constant instead of a magic number |
| one job per function | if you copy code, make a function |
# why, not what | comments explain the reason, two spaces after the code |
| no dead code | delete 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
- 140.Python Program to Rewrite Squashed Code in PEP 8 StyleEasySolve
- 141.Fix a Messy Python Program That Won't RunMediumSolve
Naming conventions
- 142.Python Program to Rename Unclear VariablesEasySolve
- 143.Fix a Variable That Hides a Python Built-in FunctionEasySolve
- 144.Python Program to Rename Functions and Constants in PEP 8 StyleMediumSolve
Indentation, spacing and line length
- 145.Fix the Indentation in a Python FunctionEasySolve
- 146.Python Program to Break a Long Line of Code (PEP 8)MediumSolve
Clean code habits
- 147.Python Program to Replace Magic Numbers with Named ConstantsEasySolve
- 148.Python Program to Replace Repeated Code with a FunctionMediumSolve
- 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.