Python Comments and Indentation
Write comments that explain intent
A comment starts with # outside quoted text and extends to the end of that physical line. Python does not execute the comment. Use comments to explain the purpose of a line or block rather than merely restating the obvious.
# Show the status before packingprint("Ready") # visible statusprint("#1")Output is Ready and #1, on separate lines. The first two # marks introduce comments; the last is inside quotes and is part of the text.
Indent statements inside a block
Indentation is the whitespace at the beginning of a line. Python uses it to determine which statements belong together. In this example if True: begins a conditional block; True means the condition is satisfied, and the colon introduces the indented body. You will learn conditions in depth later. Four spaces per indentation level is a common style, not a requirement that every valid block has exactly four spaces.
if True: print("Start") print("Work")print("Done")Start and Work belong to the conditional body; Done is outside it. All three are displayed because the condition is True. Use consistent spaces and avoid mixing tabs and spaces.
Repair an indentation error
This code fails before normal execution because the statement after the colon must belong to an indented body. Move the print line four spaces to the right (indent it by four spaces). The corrected code then displays Ready.
Inspect the block
In the earlier three-message example, remove the indentation from the second print only and predict why the remaining layout changes. Then restore both indented lines. A value-only grader cannot reliably check indentation style, so this is a manual code-reading task.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Comments and block indentation
Check your understanding of comments and indentation.
Which text is a comment in the code below?
print("#1") # statusWhich statements belong to the conditional body?
if True: print("Start") print("Work")print("Done")How should this code be repaired while keeping the conditional block?
if True:print("Ready")Why do programmers commonly use four spaces for indentation?