Python Fundamentals

How To Comment Python Code?

Comments play a key role in computer programming as they provide crucial insights into the inner workings of a program, ensuring that anyone examining the source code can easily comprehend its functionality. In Python, comments are denoted by the hash character (#) and extend to the end of the physical line. It is important to note that comments are purely for human understanding and are not interpreted by the Python interpreter. Consequently, when typing in examples, comments may be omitted, as their primary purpose is to clarify the source code for developers and readers alike.

By using comments effectively, programmers can enhance code readability, promote collaboration, and facilitate maintenance tasks, ultimately fostering a more efficient and comprehensible programming experience.

#My first comment in Python

The above line is not executed in Python .

Another example:

# Adding 2 numbers x = 10 # first variable y = 20 # second variable c = x + y # find the sum of variables print(c) #output: 30

Python Multiline comments

When dealing with comments that span multiple lines in Python, a common approach is to begin each line with the hash character (#). This method ensures that each line is treated as a separate comment, maintaining clarity and readability within the code. By consistently prefixing each line with the hash character, programmers can clearly delineate the comment section, making it easier for others to understand the intended message or purpose behind the commented code.

It is worth noting that Python does not provide a specific syntax for multi-line comments like some other programming languages. Therefore, using the hash character at the beginning of each line is a conventional practice to achieve the desired effect of multi-line comments in Python.

# This is # Multiple line # Comments example

A common way to use comments for multiple lines is to use the triple-quoted strings(''') symbol.

''' This is multiple line comment '''

Conclusion

Python does not have a specific syntax for multiline comments like languages such as C/C++ or .NET. However, Python allows the usage of multiline docstrings as a way to achieve a similar effect for commenting multiple lines of code. Docstrings are string literals enclosed in triple quotes (""") and are typically used to provide documentation or descriptions for functions, modules, or classes. While their primary purpose is to serve as documentation, they can be used as multiline comments within the code to provide additional explanations or comments about specific sections.

Guido van Rossum, the creator of Python, has indeed acknowledged and mentioned this usage of multiline docstrings as a way to effectively comment multiple lines of code in Python.