Code is read far more often than it's written: by teammates, by people answering your questions online, and by you, three weeks from now. Python's design puts readability first (remember "Readability counts." from the Zen of Python). Comments and consistent style are how you keep your own code readable.
You'll sometimes see text in triple quotes right at the top of a file or just inside a function:
python
"""Receipt printer: prints a simple shop receipt."""print("Receipt")
That's a docstring, a string that documents a module, function, or class. Unlike # comments, Python keeps docstrings so tools (and help()) can show them. You'll write them properly in the Functions module.
PEP 8 is the official style guide for Python code. (A PEP is a Python Enhancement Proposal, a design document for Python.) Almost all Python projects follow it, so following it makes your code look familiar to every Python programmer.
You don't need to memorize all of it. These are the rules that matter most right now.
Python uses indentation (spaces at the start of a line) to group code into blocks. Use 4 spaces per level, never tabs:
python
temperature = 31if temperature > 30: print("It's hot.") print("Drink water.")print("Have a nice day.")
The two indented lines belong to the if. The last line doesn't. You'll learn if properly in the Making Decisions module. For now, notice that indentation isn't just style in Python: it changes what the code means. Wrong indentation causes errors (see Common mistakes below).
Code editors insert 4 spaces when you press Tab in a .py file.
Later, you can install a formatter that fixes spacing automatically and a linter that points out style problems. For now, following these few rules by hand builds good habits.
This program works, but it's hard to read. Rename the variables, fix the spacing, and add one useful comment. Make sure it still prints the same result.
TabError: inconsistent use of tabs and spaces in indentation
The lines look aligned, but some use a tab character and some use spaces. Fix: set your editor to insert spaces (VS Code does this by default for Python). In VS Code, run Convert Indentation to Spaces from the Command Palette.
The code says 20%, but the comment says 10%. Which one is right? Fix: update comments whenever you change the code, or remove comments the code already makes clear.
Rewrite this program so it follows everything in this lesson: meaningful names, PEP 8 spacing, blank lines between sections, and one or two comments that explain why. It should print the same result.
python
W=5.5H=3r=W*Hpc=r*85000 #print ("Room cost:",pc)
Solution
python
# Room size in meterswidth = 5.5height = 3area = width * height# Flooring price in som per square meter (supplier quote)PRICE_PER_SQUARE_METER = 85000cost = area * PRICE_PER_SQUARE_METERprint("Room cost:", cost)
Names say what each value means, and the fixed price is a constant in UPPER_CASE.
Comments give units and where the price comes from, which the code can't show.
The empty # comment was removed, and the spacing around =, *, and after commas was fixed.
Comments and Code Style
What you'll learn
#, and what Python does with themWhy it matters
Code is read far more often than it's written: by teammates, by people answering your questions online, and by you, three weeks from now. Python's design puts readability first (remember "Readability counts." from the Zen of Python). Comments and consistent style are how you keep your own code readable.
Writing comments
A comment starts with
#. Python ignores everything from the#to the end of the line:#and one space after it.A
#inside a string is just a character, not a comment:Python has no special block-comment syntax. For several lines, start each one with
#:Good comments explain why
Beginners often write comments that repeat the code. Those don't help, because the code already says what happens.
Useful comments explain why the code is the way it is, or give context the code can't show:
A few rules of thumb:
d = 7with a comment is worse thandays_until_deadline = 7.Commenting out code
Putting
#in front of a line disables it without deleting it. This is useful for testing:In most editors, Ctrl + / (macOS: ⌘ + /) comments or uncomments the selected lines.
Don't leave large blocks of commented-out code in finished programs. They clutter the file, and it's unclear whether they still matter.
A quick look at docstrings
You'll sometimes see text in triple quotes right at the top of a file or just inside a function:
That's a docstring, a string that documents a module, function, or class. Unlike
#comments, Python keeps docstrings so tools (andhelp()) can show them. You'll write them properly in the Functions module.PEP 8: Python's style guide
PEP 8 is the official style guide for Python code. (A PEP is a Python Enhancement Proposal, a design document for Python.) Almost all Python projects follow it, so following it makes your code look familiar to every Python programmer.
You don't need to memorize all of it. These are the rules that matter most right now.
Indentation: 4 spaces
Python uses indentation (spaces at the start of a line) to group code into blocks. Use 4 spaces per level, never tabs:
The two indented lines belong to the
if. The last line doesn't. You'll learnifproperly in the Making Decisions module. For now, notice that indentation isn't just style in Python: it changes what the code means. Wrong indentation causes errors (see Common mistakes below).Code editors insert 4 spaces when you press Tab in a
.pyfile.Names:
snake_caselower_case_with_underscorestotal_price,user_name,print_receiptUPPER_CASEMAX_USERS,TAX_RATECapitalizedWordsShoppingCart,StudentChoose names that say what the value means:
Spaces
=and around most operators:total = price * 2.print("a", "b").print("hi"), notprint( "hi" ).=:print("a", "b", sep="-").Line length and blank lines
Tools do this for you
Later, you can install a formatter that fixes spacing automatically and a linter that points out style problems. For now, following these few rules by hand builds good habits.
Try it
This program works, but it's hard to read. Rename the variables, fix the spacing, and add one useful comment. Make sure it still prints the same result.
Common mistakes
1. Unexpected indentation
Only indent code that belongs to a block, such as the body of an
if. Fix: remove the extra spaces.2. Missing indentation
Fix: indent the body of the
ifwith 4 spaces.3. Mixing tabs and spaces
The lines look aligned, but some use a tab character and some use spaces. Fix: set your editor to insert spaces (VS Code does this by default for Python). In VS Code, run Convert Indentation to Spaces from the Command Palette.
4. Comments that lie
The code says 20%, but the comment says 10%. Which one is right? Fix: update comments whenever you change the code, or remove comments the code already makes clear.
Practice
1. Clean it up ★︎★︎★︎
Rewrite this code following PEP 8 spacing. Don't change what it prints.
Solution
2. Better names ★︎★︎★︎
Give these variables meaningful
snake_casenames:Solution
FlightPriceSomuses the class style (CapitalizedWords). Variables usesnake_case.3. Useful or noise? ★︎★︎★︎
For each comment, decide whether it's useful or noise, and explain why.
Solution
# speed: noise. The name already says it. A useful version would give the unit:# km/h.# kilometers: useful. It gives the unit, which the code can't show.# divide distance by speed: noise. It repeats the code.# add a 30-minute rest stop: useful. It explains why 0.5 is added.4. Find the bug with comments ★︎★︎★︎
This program prints the wrong total. Comment out lines one at a time to find which line causes the problem, then fix it.
The expected output is
Total fruit: 7.Solution
Commenting out
apples = 40makes the program printTotal fruit: 7. That line overwrote the correct value, so delete it:Temporarily disabling lines like this is a simple but effective debugging technique.
5. Style review ★︎★︎★︎
Rewrite this program so it follows everything in this lesson: meaningful names, PEP 8 spacing, blank lines between sections, and one or two comments that explain why. It should print the same result.
Solution
UPPER_CASE.#comment was removed, and the spacing around=,*, and after commas was fixed.Recap
#starts a comment, and Python ignores the rest of the line.snake_casenames, spaces around=and operators, lines of about 79 characters.IndentationErrororTabError.Further reading