Learning goals

  • Write comments in Python code.
  • Know that Python does not run comments.
  • Write comments that explain why, not only what.

What is a comment?

Look at this example:

import turtle as otto

# Draw one side of the square.
otto.forward(60)

The line starting with # is a comment: a note for people reading the code. Python ignores comments, so it does not run them. The turtle still moves forward 60 steps.

The symbol # starts a comment in Python.

Where can we write a comment?

Write a comment on its own line, or after a code instruction:

import turtle as otto

otto.forward(60)  # Draw one side of the square.

Python runs the code before # and ignores the comment after it.

Why are comments helpful?

Comments make code easier to read. They can explain why you wrote a line, for your teacher, a friend, or yourself.

For example, this comment explains why the turtle turns:

import turtle as otto

# Turn so Otto can draw the next side.
otto.left(90)

Keep comments short and clear. Write them where someone might need help understanding your code. Do not add a comment to every line.

Can a comment switch off code?

Put # before a code instruction to make Python skip it:

import turtle as otto

otto.forward(60)
# otto.left(90)
otto.forward(60)

The turtle does not turn. It moves forward twice in the same direction. Remove # and the space after it to make Python run the turn again.

Try it yourself: Click the Run button. The drawing appears below the code.

Then remove the # and the space after it. Click Run again. What changes in the drawing?

import turtle as otto

otto.forward(60)
# otto.left(90)
otto.forward(60)

Summary

import turtle as otto

# A comment on its own line.
otto.forward(60)  # A comment after an instruction.
Idea What it means
# Starts a comment.
Comment A note for people reading code. Python skips it.