How to comment out a block of code in Python
To comment out multiple lines in Python, simply prepend #
to each line:
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 orCmd
+/
on macOS. - Meanwhile, in IDLE, it's a matter of hitting
Alt
+3
to comment andAlt
+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:
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:
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!
Was this article helpful?