Python enables you to add comments to your code. A comment is text that appears in a script but that is marked as not to be executed. You can add comments to your code at any point. For example, as you develop a script, you might use comments to describe the tasks the code needs to perform and possible approaches for them. After finishing the script’s commands, you might rework the comments so that they explain what the script does. Such comments will help others understand and maintain the code.
Formally, Python supports only single‐line comments, but you can also use multiline strings to create informal multiline comments.
Create Formal Comments Using the # Character
Python uses the # character to mark the start of a single‐line comment. You can place the # character at the start of the line to make the entire line into a comment, as in the following example:
# display the value of y
print(y)
Alternatively, you can place the # character after some code, as in the following example. This method works better for short comments and for comments you intend to remove once you get the code working.
t = "Placeholder 1" # replace this placeholder text
You cannot use the continuation character, \, to continue a single‐line comment to the next line. Instead, type # at the beginning of the next line if you need to continue the comment, as in the following example:
# prompt the user for the company name
# compare the company name to an approved list
Using Multiline Strings to Create Informal Comments
Another way to create a multiline comment in a script is to create a multiline string but not assign it to a variable. To create a multiline string, you place three double quotes at the beginning and at the end, or three single quotes at the beginning and at the end. The following example uses three double quotes:
"""
Run an external check with the chem_verify() method
to confirm the formula is correct.
Log the formula in the standard file.
"""
This method of creating informal comments works but has no real advantage over using the # character on each line. You should know about this method not because you should use it in your own code but because you may encounter it in other people’s code.
Using Comments to Prevent Code from Executing
Apart from adding textual commentary to your code, comments have a secondary use: You can use the # character to prevent a specific line of code from executing. This is called commenting out the code —turning a statement into a comment prevents the code from running without you having to remove it from the script, but you can restore the code by removing the comment character.
For example, the # character comments out the first of the following statements:
# u = input("Type your name: ")
u = "Bob" # default name for testing
print("You are " + u + ".")
0 comments:
Post a Comment