Comments

Comments explain code and are ignored when the program runs.

Syntax# this is a comment

Comments are notes in your code that Python ignores. Use them to explain what your code does.

Writing comments

  • Anything after a # on a line is a comment.
  • Python has no dedicated multi-line comment, so you put a # on each line.
  • A triple-quoted string is often used as a block note or docstring.

Example

Example · python
# This is a single-line comment
x = 10  # set x to 10

# Each line of a
# multi-line note starts with a hash
print(x)

# Output:
# 10

When to use it

  • A developer adds inline comments to explain a complex formula so future maintainers understand it.
  • A learner comments out a print statement temporarily while debugging an error.
  • A team uses docstrings at the top of every function to auto-generate API documentation.

More examples

Inline and block comments

Shows a block comment above code and an inline comment after an expression.

Example · python
# Calculate the area of a circle
radius = 5  # in centimetres
PI = 3.14159
area = PI * radius ** 2
print(area)  # 78.53975

Comment out code for debugging

Demonstrates using a comment to temporarily disable a line without deleting it.

Example · python
x = 10
# x = 20  # disabled during debugging
print(x)

# Output:
# 10

Docstring as function note

Uses a triple-quoted docstring to document a function's purpose, readable by help().

Example · python
def greet(name):
    """Return a personalised greeting string."""
    return f'Hello, {name}!'

print(greet('Ada'))
# Output:
# Hello, Ada!

Discussion

  • Be the first to comment on this lesson.