Skip to content

Comments in Python

Comments in Python are used to provide explanatory notes within the code. They are ignored by the Python interpreter and serve the purpose of making the code more readable for developers. Comments are helpful for documenting code, explaining the purpose of specific lines, or temporarily disabling code during testing.

There are two types of comments in Python:

Single-line Comments:

Single-line comments begin with the # symbol and extend to the end of the line.

				
					# This is a single-line comment
print("Hello, World!")  # This is another comment
				
			

Multi-line Comments (Docstrings):

For multi-line comments or documentation, triple quotes (”’ or “””) are used. While these are technically string literals, they are often used as multi-line comments, especially when placed at the beginning of a module, class, or function to provide documentation (docstrings).

				
					'''
This is a multi-line comment or docstring.
It can span multiple lines.
'''

				
			
				
					"""
Another way to create a multi-line comment or docstring.
"""
				
			

Best Practices:

Use comments to explain complex sections of code or to provide context that might not be immediately obvious. Keep comments up-to-date. If the code changes, update the corresponding comments. Avoid unnecessary comments. Well-written code should be self-explanatory, and comments should enhance understanding rather than state the obvious. Examples:
				
					# Example of a simple Python program with comments

# This program prints a greeting message
def greet(name):
    # Display a personalized greeting
    print("Hello, " + name + "!")

# Get user input and call the greet function
user_name = input("Enter your name: ")
greet(user_name)
				
			

In the example above, comments are used to explain the purpose of the program, the function, and the input process. These comments provide additional information to someone reading the code.