Effective Python Code Commenting

PythonPythonBeginner
Practice Now

Introduction

Code comments can help people understand what the code is for, and good commenting habits are essential for a good developer. In this lab, you can learn how to add comments to the Python language, and several common ways to comment.

Achievements

  • Code Comments

Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-72{{"`Effective Python Code Commenting`"}} python/build_in_functions -.-> lab-72{{"`Effective Python Code Commenting`"}} end

Single Line Comments

In Python, # is used for single-line comments, which can appear at the beginning or end of a code line.

Example

Open /home/labex/project/single.py in your text editor and add a single-line comment:

## Output hello string
print('hello')

Alternatively, you can place a comment at the end of the code line:

print('hello') ## Output hello string

Single-line comments are valuable for providing explanations and clarifications in your code. They are ignored during execution and serve as helpful documentation for both yourself and others.

Multi Line Comments

For more extensive comments, Python utilizes three single quotes ''' or three double quotes """ for multi-line comments.

Example

Open /home/labex/project/multi1.py in your text editor and add a multi-line comment using single quotes:

'''
This is a multi-line comment using single quotes.
It can be used to provide detailed explanations or instructions.
'''
name = "Tom"
print("Hello, " + name + "!")

Alternatively, open /home/labex/project/multi2.py in a text editor and add a multi-line comment in double quotes:

"""
This is a multi-line comment using double quotes.
It can be used to provide detailed explanations or instructions.
"""
name = "Tom"
print("Hello, " + name + "!")

Multi-line comments enhance code readability and are particularly useful when detailed explanations are required. They serve as valuable documentation within your code.

Summary

Congratulations! You have completed the Python Comments Lab.

In this lab, you have learned how to add Python single-line and multi-line comments.

Other Python Tutorials you may like