Comments#
Overview#
Comments are lines that explain the code steps, and are not executed by Python interpreter. A good set of comments can make a huge difference in the code interpretation and debugging.
Tip
Comments start with the # character and extend to the end of the line
Comments are ignored by the interpreter and do not impact the execution of the program
Comments can be placed at the end of a line of code
Comments are not limited to the English language
Let’s add comments:
# This is a comment explaining the purpose of the following code
x = 5 # Assigning a value to the variable x
print(x)
# This code calculates the sum of two numbers
result = 10 + 5
print(result)
# This line is commented out and won't be executed
print("Hello, World!") # This line is commented out and won't be executed
5
15
Hello, World!
Multiline comments#
Multiline comments, also known as block comments or docstrings, are used to provide longer descriptions for functions, classes, modules, or entire programs. Unlike single-line comments, there are two common ways to create multiline comments in Python:
Using triple quotes (
"""
or'''
):The opening and closing triple quotes must be on separate lines, and the comment text can span multiple lines in between.
"""
This is a multiline comment or docstring.
Multiple lines are typically used to provide longer documentation.
"""
Another way to create a multiline comment is by using the # symbol at the beginning of each line.
# This is a multiline comment or docstring.
# It can span multiple lines and is typically used
# to provide documentation for functions, classes, or modules.