Menu

A comment is a note written inside a program for the people who read the code. It might explain what a section does, why an approach was chosen, or what an odd-looking value means. Comments are not instructions to the user, and they are not part of the program's logic.

The translator ignores every comment: comments are stripped out before the code runs, so adding, changing or deleting one never alters the program's output or behaviour. A comment exists purely to help a human being understand what is going on.

How to write a comment in Python

In Python a comment starts with a hash symbol #. Everything from the # to the end of that line is treated as a comment, so a comment can sit on its own line above the code it describes or at the end of a line of code.

# Work out the price of a cinema trip for a group
number_of_tickets = int(input("How many tickets? "))
ticket_price = 6.50

# Groups of four or more get a 10% discount
if number_of_tickets >= 4:
    total = number_of_tickets * ticket_price * 0.9
else:
    total = number_of_tickets * ticket_price

print(total)  # price after any discount

Output when the user types 3:

How many tickets? 3
19.5

Why commenting helps

Programs are changed far more often than they are first written. A maintainer — the original programmer months later, or somebody else taking over — must work out what the code was meant to do before safely fixing a bug or adding a feature. Comments that explain a section's purpose make that quicker and reduce the chance of a change breaking something. They help with debugging too, because a note saying what a block should produce makes it easier to spot where it goes wrong.

Good comments and weak comments

The best comments explain purpose or logic — the reason behind the code. Weak comments simply repeat what the line already says, or give instructions to a user instead of explaining the code.

  • Useful: noting that a total is multiplied by 1.2 to add delivery and packing charges.
  • Useful: noting that a loop keeps asking until the value is within the permitted limits.
  • Weak: writing # add one to counter above counter = counter + 1, which is already obvious.
  • Weak: writing # type your name below, which instructs the user rather than describing the code.

Commenting sits alongside sub programs, meaningful naming conventions and indentation as a way of making a program easier to maintain, but it does not change what the program does.

Practise this