Python Comments
Comments are notes in your code that Python ignores when it runs the program.
Why Use Comments?
- To explain what a piece of code does, or why you wrote it that way
- To help other people (and your future self) understand the code
- To switch off a line for a moment while you test something
Single-Line Comments
A comment starts with the hash sign #. Everything after # on that line is ignored.
Example
# This program calculates the price of 3 notebooks
price = 120 # price of one notebook in Rs
print(price * 3)360
The first line is a full-line comment. The second comment sits at the end of a line of code. Both are skipped by Python.
Comments to Disable Code
Put # in front of a line to stop it from running, without deleting it:
Example
print("Line one")
# print("Line two")
print("Line three")Line one Line three
This is helpful when you look for a mistake. You can switch lines off and on again quickly.
Multi-Line Comments
Python has no special symbol for multi-line comments. The simple way is to start every line with #:
Example
# This program is for Ayesha's bakery.
# It adds the price of cakes and biscuits
# and prints the total bill.
cakes = 1200
biscuits = 350
print(cakes + biscuits)1550
You may also see text inside triple quotes """ used as a comment. If this text is not stored in a variable, Python ignores it:
Example
"""
Bakery bill calculator
Version 1
"""
print("Ready")Ready
Triple-quoted text at the start of a function has a special name: a docstring. You will learn about it in the Functions lesson.
Good Comment Habits
| Do | Avoid |
|---|---|
| Explain the reason behind the code | Repeating what the code already says clearly |
| Keep comments short | Long stories inside the code |
| Update comments when the code changes | Old comments that no longer match |
A comment like x = x + 1 # add one to x adds nothing. A comment like # skip the header row tells the reader something useful.
Exercise
Exercise
Which character starts a comment in Python?
