PYTHON

Python Comment: Syntax, Usage, and Examples

In Python, comments are non-executable statements to annotate and explain the code to make it easier to understand. Comments get ignored by the Python interpreter.

How to Use Comments in Python

To add a comment, simply use the hash symbol (#) along with your comment's text. The Python interpreter ignores any characters following the # on the same line.

# This is a single-line comment
print("Hello, world!")  # This is a comment after code

When to Use Comments in Python

Comments are an important tool to keep Python programs maintainable. Especially in collaborative settings or when you might need to update code after a long period, comments are essential.

Code Explanation

Comments can explain what the code does. Such explanations help other developers understand your code or reminds you if you revisit the code later.

# Calculate the square of a number
square = 5 ** 2

Code Documentation

In larger projects, comments often document the functionality of functions, classes, and modules in detail.

def add(a, b):
    # Return the sum of two numbers
    return a + b

Debugging

Temporarily commenting out parts of code is another common use of comments. During debugging, you can comment out code to isolate parts of a program.

# print("This line is commented out and won't execute")
print("This line runs and will print to console")

Examples of Using Comments in Python

Comments are a commonplace in any Python application. Here are some examples of comments you might run into:

TODOs and FIXMEs in Open Source Projects

Open-source projects (but also other software) might use comments to note enhancements, bugs, or improvements for the future.

# TODO: Optimize this loop for large datasets
for i in range(10000):
    print(i)

Complex Algorithms

For a complex algorithm, comments might describe steps or logic, making the code easier to follow and maintain.

# Step 1: Initialize the sum variable
sum = 0
# Step 2: Loop through numbers 1 to 10
for num in range(1, 11):
    # Step 3: Add number to sum
    sum += num
# Step 4: Print the final sum
print("Sum is:", sum)

Legal or Licensing Comments

At the start of a script or file, comments often include copyright and licensing information.

# Copyright 2024 Mimo GmbH

Learn More About Comments in Python

Python Multiline Comment

Python lacks a specific multiline comment syntax like other programming languages. To create a multiline comment in Python, you can use multiple single-line comments or a triple-quoted string using ''' or """.

"""
This is a multi-line comment
using a triple-quoted string.
"""
print("Hello, Python!")

Unless assigned to a variable, triple-quoted strings are ignored by the Python interpreter. Technically, however, they’re not comments.

Python Block Comment

Block comments in Python explain the code that follows them and are typically indented to the same level as the code.

def factorial(n):
    """
    Calculate the factorial of a number
    Argument:
    n -- integer
    Returns:
    n! -- factorial of n
    """
    if n == 0:
        return 1
    else:
        return n * factorial(n-1)

How to Comment Out Multiple Lines in Python

In Python, commenting out multiple lines of code at once is a common need. Common scenarios are during debugging or when you want to disable certain parts of your code temporarily.

Most Python IDEs and editors support commenting out selected blocks of code with a keyboard shortcut. For example, in Visual Studio Code, you can select multiple lines and use CTRL + / (Windows) or CMD + / (macOS) to toggle comments on and off.

# This is the first line commented out
# This is the second line commented out
# print("These lines are not executed")

If your IDE has no shortcut for commenting out code, you can also use a triple-quoted string (''' or """). Such multi line comments are useful when the number of lines is too large for single-line comments to be practical.

"""
print("This line is commented out.")
print("This line is also commented out.")
This block will not affect the runtime unless syntax errors are present inside.
"""

Best Practices for Commenting

Good comments explain "why" the code does something rather than "how" it does it. Effective comments are concise and relevant, aiding understanding without overwhelming the reader. Over-commenting can clutter the code and reduce readability, so it's important to find a balance.

# BAD: Increment i by 1
i += 1

# GOOD: Handle edge case where i needs manual increment
i += 1
Learn to Code in Python for Free
Start learning now
button icon
To advance beyond this tutorial and learn Python by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

You can code, too.

© 2024 Mimo GmbH