Explain Codes LogoExplain Codes Logo

How to comment out a block of code in Python

python
commenting
best-practices
ide-shortcuts
Nikita BarsukovbyNikita Barsukov·Aug 13, 2024
TLDR

To comment out multiple lines in Python, simply prepend # to each line:

# print("These lines") # print("Don't mind me, just a comment passing through.")

The above standard way of doing it is the most reliable and prevalent among Python enthusiasts.

Ways to comment: a deep dive

To give your code a good "don't run just yet" treatment, you've got a variety of tricks up your sleeve. Let's explore:

IDE shortcuts: Your magic wand

Python IDEs offer a wand with keyboard shortcuts that can swath a block of code in glorious invisibility.

  • PyCharm users can swiftly transform their code into comments with Ctrl + / on Windows or Cmd + / on macOS.
  • Meanwhile, in IDLE, it's a matter of hitting Alt + 3 to comment and Alt + 4 to take the comment off.

The 'if False': a temporary fix

How about an impermeable shield of inactivity using if False:? In this scenario, the code doesn't stand a snowball's chance in Vulcan of getting executed:

if False: print("Hey, why am I not running? Oh, I remember!") sum_of_life = 42 # This guy knows the secret!

Remember to carry your umbrellas — your code must still be syntactically waterproof under these conditions!

Embracing and releasing triple-quotes

The power of triple-quotes (''' or """) can transfigure blocks of code into temporary walls of silence. Well, it seems like magic, but you're really just casting a docstring, and it's only good for a test flight:

""" print("Just chilling here, catching some zZz's.") sum_of_universe = infinite # E=mc^2 anyone? """

Don't let this trick dazzle you though — docstrings have a day job in your final spellbook, aka production code.

Annotating like a pro

Keep your codebase as clean as a new broomstick by sticking to the Marauder's Map of best practices.

Adherence to the PEP 8

According to the PEP 8 Harry Potter edition, writing block comments should be done as often as seeing a Thestral — only when absolutely necessary!

Mindful strategies

Choose a commenting technique that doesn't break your invisibility cloak (aka code readability and functionality). You don't want your map to be filled with mischief!

Consider the owl post

Triple-quotes might seem handy for comments until your doc generators receive the wrong owls (messages). So, be careful while leaving footprints in your code!

Clarity > Cleverness

In the world of magic (or coding), clarity always beats cleverness when it comes to comments. You're writing for humans, not trolls!

Automagic to the rescue

Ace coders at Hogwarts might swear by their old faithful vi and emacs spell-checkers, but even for muggle-born coders, mastering your IDE's shortcuts could save you endless minutes!