Python Comments Single-Line and Multi-Line Commenting Explained
Python single and multiline commenting
Python Tutorial > Python Comments > Python Block Comments > Python Comments: Single-Line and Multi-Line Commenting Explained
Posted in

Python Comments: Single-Line and Multi-Line Commenting Explained

Learn everything about Python comments in this detailed guide. Understand single-line and multi-line commenting, inline comments, best practices, examples, and when to use each style. Perfect for beginners and intermediate Python learners.

Introduction

Python Comments

Single-line Comments in Python

Syntax of a single-line comment
# This is a single-line comment
print(‘Hello World!’)
# Store the user age
age = 25

print(age)
# print("This line is commented out and will not run.")
print("This line will execute normally.")
  • The second line runs normally and prints the output.
# The following line is commented out and will NOT execute
# result = 10 / 0   # This would cause a ZeroDivisionError

print("Program continues without running the commented-out code.")
# print("Debug: user_data =", user_data)
print("Processing completed.")
def greet():
    print("Hello!")

# greet()  # Disabled for now
print("Program continues...")
for i in range(3):
    # print("Loop iteration:", i)  # Disabled debug output
    print(i)
# a = 42
b = 10
print(b)
is_admin = False

# if is_admin:
#     print("Access granted")

print("Access denied")
# -------------------------
# 1. Import Dependencies
# -------------------------
import math
import random


# -------------------------
# 2. Define Helper Functions
# -------------------------
def calculate_area(radius):
    return math.pi * radius ** 2

def get_random_number():
    return random.randint(1, 10)


# -------------------------
# 3. Main Program Logic
# -------------------------
radius = 5
area = calculate_area(radius)
number = get_random_number()


# -------------------------
# 4. Output Results
# -------------------------
print("Area:", area)
print("Random Number:", number)

Inline Comments (Subtype of Single-Line Comments)

price = 499  # Product price in USD
# Calculate the total price including tax   ← single-line comment

price = 100       # base price
tax_rate = 0.18   # 18% tax rate (inline comment)

total = price + (price * tax_rate)  # calculate final amount (inline explanation)

print("Total:", total)  # output result
# Loop through numbers and print only even ones   ← single-line comment

for num in range(1, 6):
    if num % 2 == 0:  # check if number is even (inline comment)
        print(num)    # print even number
# Function to calculate the square of a number   ← single-line comment

def square(n):
    return n * n  # multiply number by itself (inline comment)

result = square(4)  # call function
print(result)       # output result
price = 499  # This price is set because the company decided in 2020 that...

Multiline Comments in Python

Method 1: Using multiple single-line comments (#) — also known as Block Comments

# This block of comments explains the next section of code.
# We are validating user input and checking if the age
# is within a realistic human range.
# If not, we raise a ValueError.
# -------------------------------
# Block comment describing a task
# This section calculates the area
# -------------------------------

radius = 5
area = 3.14 * radius ** 2
print(area)
# Check if the number is prime:
# 1. Numbers less than 2 are not prime
# 2. Check divisibility from 2 to sqrt(n)
# 3. If divisible, it's not prime

num = 11
# The following lines are disabled
# during debugging or testing
# print("This won't run")
# print("This is also commented out")

print("Program continues...")
# This block explains how user authentication works:
# - First, the system checks stored credentials.
# - Then, it validates the password hash.
# - Finally, it generates a session token.

authenticate_user()

Method 2: Using Triple-Quoted String Literals (Pseudo Multiline Comments)

print('Multiline Comments')

"""
This is multiline comments
We are using # in each line
Multiple single-line to make multiline comment
"""
print('Multiline Comments')

'''
This is multiline comments
We are using # in each line
Multiple single-line to make multiline comment
'''
print('Multiline Comments')
"Unassign string"
"""This is a module docstring"""

print('Multiline Comments')
print(__doc__)
Multiline Comments
This is a module docstring

Not an Example of Multiline Comments

x = 10
# Here x is a variable
y = 10
# Here y is a variable
z = x + y
# z consist addition of both variables
print(z)
# printing the value in the output
x = 10
y = 10
z = x + y
print(z)
'''
Here x and y are variables.
We are adding both variables and storing the result in z.
Finally, we print the value of z in the output.
'''
x = 10
y = 10
z = x + y
print(z)
# Here x and y are variables.
# We are adding both variables and storing the result in z.
# Finally, we print the value of z in the output.

Difference in Placement of Triple Quotes

# Same line
s1 = '''This is a multiline comment
written using
triple single quotes'''

# New line
s2 = '''
This is a multiline comment
written using
triple single quotes
'''

print(repr(s1))
print(repr(s2))

Output

'This is a multiline comment\nwritten using\ntriple single quotes'
'\nThis is a multiline comment\nwritten using\ntriple single quotes\n'

Single-line vs Multi-line Comments in Python

FeatureSingle-line Comment (#)Multi-line Comment (Triple Quotes ''' / """)
SyntaxStarts with #Enclosed in ''' ''' or """ """
PurposeBrief, one-line explanationsLonger explanations, spanning multiple lines
Runtime effectIgnored by interpreterTreated as a string literal, ignored if not used
Typical use caseExplain why code does something, inline clarification, quick TODOsPublic API documentation (docstrings) or multiline literal data; not recommended as general comments
Best practicePreferred for comments; use one # per line for blocksUse only for docstrings; avoid using as block comments in the middle of code
Inline useCan appear after code on the same lineCannot appear inline with code
Examplex = 5 # current value"""This function adds two numbers."""

PEP 8 Guidelines for Python Comments

# Calculate the average score
# Exclude outliers below 0 and above 100
scores = [78, 92, 85, 63, 95]
average = sum(scores) / len(scores)
print(average)

Conclusion

Next Post
Python Comments: Frequently Asked Questions (Ultimate FAQ Guide)

Suggested Posts
1. Python Comments: The Complete Guide (Types, PEP 8, Best Practices & Examples)
2. Python Comments: Frequently Asked Questions (Ultimate FAQ Guide)

3 thoughts on “Python Comments: Single-Line and Multi-Line Commenting Explained

Leave a Reply

Your email address will not be published. Required fields are marked *