CodeBlanks Logo Icon CodeBlanks

Comments

Learn single-line (#) and multi-line (triple-quote) comments.

Why write comments?

Comments are text that Python ignores but explains the code to humans. Comments help you remember what code does later and help others understand it.

A single-line comment starts with the # sign. Everything from # to the end of the line is a comment:

# This is a comment
print("Hello")

Comments support code, they do not replace it. Clear variable names cannot replace a comment, but a good comment always helps.

Multi-line comments

Python has no separate syntax for multi-line comments. Instead we put # at the start of each line, or we use a triple-quoted string:

# This comment spans
# multiple lines

A triple-quoted string is actually a string; but when it is not assigned to a variable, Python ignores it. So it is used for documentation:

"""This is a
doc string"""

The docstring is the topic of a later lesson.

Practice Add a comment

Print Welcome to the screen with print. Add a # Greeting message comment above it.

Starter code

main.py
# Add a comment

Sample solution

main.py
# Greeting message
print("Welcome")

Expected output

Welcome

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the comment line

Question
# This line is a ____ line
Answer
# This line is a comment line

Explanation: A line starting with # is a comment.

2 Which of these is a valid Python comment?

  • <!-- Comment -->
  • // User input
  • # User input Correct answer
  • /* Comment */

Explanation: A Python single-line comment starts with #.

3 Match each item to its purpose

Term Meaning
# Single-line comment
""" Triple-quoted string
exit() REPL exit
python3 Start the REPL

All lessons in Beginner