Python Comments

Python Comments

Suriya Ravichandran


Python Comments

Comments in Python are used to add notes inside your code. They help developers understand what the code is doing, make programs easier to read, and allow you to temporarily disable parts of the code during testing or debugging.

Python completely ignores comments while executing a program, so they do not affect the output.

Writing a Single-Line Comment

In Python, a comment begins with the # symbol. Anything written after # on that line is treated as a comment and is skipped during execution.

Example:

Try it Yourself

Inline Comments

Comments can also be placed on the same line as a statement. In this case, Python executes the code before # and ignores everything that follows it.

Example:

Try it Yourself

Inline comments are helpful for briefly describing a specific line of code.

Using Comments to Disable Code

Comments can be used to stop certain lines of code from running without deleting them. This is commonly done while testing or debugging.

Example:

Try it Yourself

Only the uncommented line will run when the program is executed.

Multi-Line Comments in Python

Python does not have a dedicated syntax for multi-line comments. However, there are two common ways to write them.

Method 1: Multiple Single-Line Comments

The most recommended approach is to use # at the beginning of each line.

Example:

Try it Yourself

Method 2: Using Multi-Line Strings

Another approach is to use triple quotes (""" """ or ''' '''). Python treats these as string literals. If they are not assigned to any variable, they are ignored during execution.

Example:

Try it Yourself

Although this method works, it is mainly intended for documentation strings (docstrings) rather than regular comments.

Our website uses cookies to enhance your experience. Learn More
Accept !