Python Tutorial menu

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

python
# This program calculates the price of 3 notebooks
price = 120   # price of one notebook in Rs
print(price * 3)
Output
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

python
print("Line one")
# print("Line two")
print("Line three")
Output
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

python
# 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)
Output
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

python
"""
Bakery bill calculator
Version 1
"""
print("Ready")
Output
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

DoAvoid
Explain the reason behind the codeRepeating what the code already says clearly
Keep comments shortLong stories inside the code
Update comments when the code changesOld 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?

Learn Python with a teacher

Join the Python Programming course at Workownix, online or in Orangi Town, Karachi, and get a certificate.

See the course Ask on WhatsApp