In Python (or any other programming language), comments are used to explain the source code. Comments describe the code, which helps in maintaining the application in the future for ourselves and others.
In Python, comments come in two primary forms: single-line comments and multiple-line comments. Let us learn in detail.
1. Single-Line Comments in Python
Single-line comments in Python begin with a #
(hash) symbol and continue until the end of the line. When executing the program, Python ignores everything after the #
symbol on a line. Single-line comments are ideal for adding brief explanations or notes to specific lines of code.
Here’s an example of a single-line comment in Python:
2. Multi-line Comments in Python
Python does not provide a built-in syntax for traditional block comments (such as Java comments). However, developers often use multi-line strings enclosed in triple quotes (single or double) as a workaround to create multiple-line comments.
While these are not officially the comments, these docstrings serve the purpose of providing explanations for larger blocks of code. Python ignores string literals that are not assigned to any variable, and so it will not affect the program execution.
Otherwise, we can use the # character to write multi-line comments as well.
3. Commenting Shortcuts
Python also offers some convenient shortcuts for commenting code. These shortcuts are helpful when we want to temporarily disable or comment out a block of code during debugging or testing:
We can comment out multiple lines of code by selecting them and then pressing Ctrl
+ /
(on Windows/Linux) or Cmd
+ /
(on macOS) in many popular code editors and IDEs.
This action inserts #
symbols at the beginning of each selected line, effectively commenting them out. Repeating the same shortcut uncommented the lines.
Drop me your questions related to writing comments in Python.
Happy Learning !!
Comments