Comments in Python
What are comments? Comments are notes that you write in your Python code to help humans understand it. The computer ignores comments when running the code.
Why are comments important?
Benefits of using comments:
- To understand the code: Comments help others (and yourself) understand the code.
- To improve readability: Well-commented code is easier to read.
- For testing and debugging: You can use comments to temporarily disable parts of the code for testing.
Types of Comments in Python
Python mainly supports two types of comments:
- Single-line Comments: Written using
#
. Everything after#
is ignored by Python. - Multi-line Comments: Written using triple quotes (
"""
or'''
). Everything inside these quotes is ignored by Python.
There are other ways, such as docstrings, but these two are the most common.
How to Write Comments?
Using #
and """
in Python:
1. Single-line Comments
Use #
for single-line comments.
# This is a single-line comment print("Hello, world!") # This explains the print statement
Note: Everything after #
is ignored by Python.
2. Multi-line Comments
Use triple quotes for multi-line comments.
""" This is a multi-line comment. It can span multiple lines. Python ignores everything inside these quotes. """ print("Learning Python is fun!")
Note: Everything inside triple quotes is treated as a comment.
Practice Example
Here’s a simple example using comments:
# This program calculates the area of a rectangle # Define the length and width length = 5 # Length of the rectangle width = 3 # Width of the rectangle """ Now we calculate the area. Formula: length * width. """ area = length * width # Print the result print("The area of the rectangle is:", area)
Try this: Copy this code into Python and run it to see how comments help explain the code.