A comment is source text ignored during execution and written for human readers. In Python, anything following # is normally a comment, except # inside a string, where it remains ordinary string data. section 4.2 section 4.12
Use comments to clarify code without confusing them with documentation strings:
- Explain a specific or internal choice, such as why a list must be sorted before calculating a median. section 5.9.3
- Keep comments focused and necessary; comments that merely repeat an obvious statement add little value. section 5.9.3
- Use a docstring instead when documenting a module, function, method, or class for tools and readers of its interface. section 3.5 section 9.1
Syntax and the string exception
# Assign 5 to x x = 5 x = 3 # Now x is 3 x = "# This is not a comment" section 4.2
Comment or docstring?
def clean_line(line): """Changes case and removes punctuation.""" # Make all text one case cleaned_line = line.lower() return cleaned_line The comment is discarded when the code loads. The docstring becomes the function’s __doc__ value and can be used by help() and documentation tools. section 9.9.2 section 9.1
# Assign 5 to x x = 5 x = 3 # Now x is 3 x = "# This is not a comment"
Inspect a compact listing showing full-line comments, an end-of-line comment, and a # character preserved inside a string. section 4.2









