How to comment out a block of code in Python


There are a few ways in which we can comment out a block of code in Python, let's take a look at them with examples.


Example 1: Triple Quotes - Multi-line Comments (''')

'''
def add_numbers(a, b):
    no1 = a
    no2 = b
    sum = no1 + no2
    return sum
'''


def diff_numbers(a, b):
    no1 = a
    no2 = b
    diff = no2 - no1
    return diff


result = diff_numbers(5, 10)
print("Result:", result)

Example 2: Single line Comments (using #)
# def add_numbers(a, b):
#     no1 = a
#     no2 = b
#     sum = no1 + no2
#     return sum


def diff_numbers(a, b):
    no1 = a
    no2 = b
    diff = no2 - no1
    return diff


result = diff_numbers(1, 2)
print("Result:", result)
Commenting Multiline Code in Python Example


Comment/Uncomment Code using IDE Keyboard Shortcuts:


IDEComment Code (Mac)Comment Code (Windows)Uncomment Code (Mac)Uncomment Code (Windows)
Visual Studio Code⌘ + /Ctrl + /⌘ + /Ctrl + /
PyCharm⌘ + /Ctrl + /⌘ + /Ctrl + /
Spyder⌘ + 1Ctrl + 1⌘ + 1Ctrl + 1
Sublime Text⌘ + /Ctrl + /⌘ + /Ctrl + /
Atom⌘ + /Ctrl + /⌘ + /Ctrl + /
Jupyter Notebook⌘ + /Ctrl + /⌘ + /Ctrl + /
IDLE⌘ + 3Ctrl + 3⌘ + 4Ctrl + 4

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap