How to comment out a portion of code in Python

We are going to discuss how to comment out a portion of code in Python, in this tutorial. We add comments to explain the code or to avoid getting the code complex.

It is always good to use comments in the code. It is easy to maintain, improves readability, and does not affect the code. It makes the users easy to understand.

Comment out a portion of code in Python

A portion of code includes multiple lines of code in a group. There appear some situations like debugging or something, without removing those lines and rewriting, we can comment out a portion of code.

You can learn different ways and even shortcuts to comment out a portion of code.

Python has no block comments inbuilt. To do this, we need to use #(hash) or String Triple Quotes(“””). There are some shortcuts as well in different IDE we can use.

Hash Symbol (#)

We need to put the #(Hash) symbol before starting each line of code. This is the common way to comment out a line. Python interpreter ignores the lines starting with hash.

#Comment out a portion of code




Some Shortcuts for different IDE

First, you need to select the lines you want to comment out or uncomment. Then use ‘ctrl + /’ for most cases.

But for spyder IDE use ‘ctrl + 4’ to comment and ‘ctrl + 1’ to uncomment.
For IDLE use ‘ctrl + D’ to comment and ‘ctrl + shift + D’ to uncomment.


String Triple Quotes (“””)

String triple quotes are multiple line string using double quotes (“””string”””) or single quotes (”’string”’). Inside of these quotes, the code is assumed as a string. It does not execute in the interpreter.

We need to add “”” or ”’ before starting and ending of a portion of code to make it comment lines. Be careful, you need to put the same quote style in both places.

""" For double 
b=7 """
''' For single quote 



This triple quotes way is not recommended usually, as using this, programmers can face problems. For quick ways, this is effective for small projects or debugging purposes.

Hope it is useful!

See also:
Add space after dot or comma in Python string

Leave a Reply

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