Add Comments in Python

PythonBeginner
Practice Now

Introduction

In this lab, you will learn the importance and practical application of comments in Python. Comments are essential for making your code understandable, which is crucial for maintenance and collaboration. You will explore different types of comments, including single-line and multi-line comments, and learn how to use them effectively to improve code readability.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 97% completion rate. It has received a 96% positive review rate from learners.

Understand the Purpose of Comments

Comments are notes within your code that are ignored by the Python interpreter but are valuable for human readers. They help explain the code's logic, purpose, and any non-obvious details. While a machine executes the code, it is humans who must read and maintain it. Good commenting habits are essential for writing clean and understandable programs.

Let's start with a simple script without any comments. In the WebIDE, locate the file purpose.py in the file explorer on the left panel and open it.

Add the following code to the purpose.py file:

x = 10
y = 20
z = x + y
print(z)

Save the file by pressing Ctrl + S.

To run the script, open the integrated terminal in the WebIDE by navigating to the top menu and selecting Terminal -> New Terminal. The terminal will open at the bottom of the screen, and the default path is ~/project.

Execute the script by running the following command in the terminal:

python purpose.py

You will see the output of the calculation:

30

This script is straightforward, but in a larger program, it might not be immediately clear what x, y, and z represent. In the next step, we will add comments to make this code easier to understand.

Use Single-Line Comments

Single-line comments are used for short, explanatory notes. In Python, a single-line comment begins with the hash symbol (#). The interpreter ignores everything on the line that follows the #. These comments can be placed on a separate line to describe the code below or on the same line as a statement to explain it.

Let's modify the purpose.py file to include single-line comments. Open purpose.py in the editor and update its content to the following:

## This script calculates the sum of two numbers

x = 10  ## Assign the integer 10 to variable x
y = 20  ## Assign the integer 20 to variable y
z = x + y  ## Calculate the sum of x and y
print(z) ## Print the final result to the console

Save the file (Ctrl + S) and run it again from the terminal:

python purpose.py

The output will be the same as before:

30

As you can see, the comments did not change the program's behavior. However, the code is now much more readable. The first comment explains the script's overall purpose, while the inline comments clarify the role of each line.

Use Multi-Line Comments

For longer explanations that span multiple lines, you can use a multi-line comment format. Although Python does not have a specific syntax for multi-line comments like some other languages, you can use multi-line strings for this purpose.

A multi-line string is created by enclosing text in triple quotes, either """...""" (double) or '''...''' (single). If this multi-line string is not assigned to a variable, the Python interpreter will ignore it, effectively making it a comment. This is a common convention for writing block comments or function documentation (docstrings).

Find and open the file multiline.py in the WebIDE. Add the following code:

"""
This is a multi-line comment using triple double quotes.
This script demonstrates how to write comments that span
several lines to provide more detailed explanations.
"""

message = "Hello, Python learners!"
print(message)

Save the file and run it from the terminal:

python multiline.py

You will see the following output:

Hello, Python learners!

The block of text within the triple quotes was ignored, and only the print statement was executed. This technique is very useful for providing detailed descriptions at the beginning of a file or before a complex function.

Use Declaration Comments

Python also supports special comments known as declaration comments. These are processed by the interpreter or the operating system to configure how the script runs. Two common examples are the shebang and the encoding declaration.

  1. Shebang (#!): The shebang line is the very first line of a script. It tells a Unix-like operating system which interpreter to use to execute the file. For a Python 3 script, this is typically #!/usr/bin/python3. This allows you to run the script as a standalone executable.

  2. Encoding Declaration: This comment tells the Python interpreter which character encoding to use for the source file. It is important if your code contains non-ASCII characters. The standard declaration for UTF-8 is ## -*- coding: utf-8 -*-. It should be placed on the first or second line of the file.

Let's create a script that uses both. Open the file declaration.py in the editor and add the following code:

#!/usr/bin/python3
## -*- coding: utf-8 -*-

## This script demonstrates declaration comments and non-ASCII characters.
print("Hello, World!")
print("你好,世界!") ## A greeting in Chinese

Save the file. Before you can run this script directly, you need to make it executable. In the terminal, run the chmod command:

chmod +x declaration.py

Now, you can execute the script directly without typing python first:

./declaration.py

The output will correctly display both lines of text, including the Chinese characters:

Hello, World!
你好, 世界!

The shebang line allowed the system to find and use the Python 3 interpreter, and the encoding declaration ensured the non-ASCII characters were handled correctly.

Summary

In this lab, you have learned how to add comments to your Python code. You practiced using single-line comments with # for brief notes, multi-line comments with """...""" for longer descriptions, and special declaration comments like the shebang and encoding declaration to configure script execution. By effectively commenting your code, you make it more readable, maintainable, and easier for others (and your future self) to understand.