A3. Python Statements and Comments
In this Doc, we are going to learn about :
- Python statements,
- Why do we use them, and
- How to use comments in the right way.
Comments in Python
In computer programming, comments statements/documents which we make to make our code more readable, and help us understand the logic.
Comments are completely ignored by the python interpreter. They are meant for you or your comrades.
For Example :
# declare and initialize two variables a = 6 b = 9 # print the output print('This is output')
The following comments are :
- declare and initialize two variables
- print the output
Types of Comments in Python
In Python, there are two types of comments:
1. Single-line Comment in Python
A single-line comment starts and ends in the same line. We use the # symbol to write a single-line comment. For example,
# create a variable name = 'Elon Musk' # print the value print(name)
Here, we have created two single-line comments:
- create a variable
- print the value These are both single-line comments.
We can also use the single-line comment along with the code.
name = 'Elon Musk' # name is a string
Here, the output remains the same, just a different way of writing it.
2. Multi-line comment in python
Unfortunately, Python doesn’t offer a different way to write multiline comments. However, there are ways to get around this issue.
i. We can use # at the beginning of each line of comment on multiple lines. For example,
# This is a # multiline comment # we use it multiple times
In this case, each line is treated as a separate comment and ignored by the interpreter.
ii. An alternative method is to use triple quotes ’’’ or """ for multi-line comments. These quotes are typically used for strings, but when not assigned to a variable or function, they can serve as a comment and are ignored by the interpreter.
For example :
""" This is a multiline comment we use it multiple times """
How to Use Comments in python
In this case, the multiline string is not assigned to any variable and thus, it is not considered by the interpreter. However, it can still be used as a multiline comment.
Enhancing Code Understandability Incorporating comments in our code can greatly improve its understandability, both for future reference and for other developers who may work on the project.
Utilizing Comments for Troubleshooting When encountering errors during program execution, instead of deleting the problematic line, we can simply comment it out for further analysis.
print('Yo wassup ') # print('Dream on ') print('Elon Musk')
In this example, commenting out print(‘Dream on’) allows the program to run without any issues, while still allowing us to investigate the source of the error. This demonstrates how comments can serve as an effective tool for debugging.