Python Comments
Comments are non-executable statements written in a Python program to explain the code. Python ignores comments during program execution. Comments make programs easier to understand, read and maintain.
Why Use Comments?
- To explain the purpose of a section of code.
- To make the program easier to understand.
- To document important information about the program.
- To temporarily disable a line of code during testing.
Single-Line Comments
A single-line comment starts with the # symbol.
Everything written after # on that line is treated as a comment.
# This is a comment
print("Hello Python")
Hello Python
Comment After a Statement
A comment can also be written on the same line after a Python statement.
x = 10 # Store 10 in x
print(x) # Display the value
10
Comments in Multiple Lines
Python does not have a separate multi-line comment symbol. Multiple
single-line comments can be written by using # on each line.
# Calculate the area of a circle
# radius is given by the user
# Formula: area = 3.14 * radius * radius
radius = 5
area = 3.14 * radius * radius
print(area)
78.5
Using Triple Quotes
Triple-quoted strings using ''' or """ can span
multiple lines. They are mainly used for docstrings in Python.
They should not be treated as the normal way of writing comments.
"""
This is a multi-line string.
It can contain several lines.
"""
print("Python")
Python
Comments in Functions
Comments can be used to describe what a function does.
def add(a, b):
# Return the sum of two numbers
return a + b
print(add(10, 20))
30
Commenting Out Code
A line can be temporarily disabled by placing # before it.
print("Start")
# print("This line will not execute")
print("End")
Start End
Important Points
- Use
#for a single-line comment. - Python does not execute comments.
- Comments improve code readability.
- Comments can be written before or after a statement.
- Use meaningful comments that explain the code clearly.
# symbol is the standard way
to write a comment in Python.