leafleafleafDocy banner shape 01Docy banner shape 02Man illustrationFlower illustration

Python comments

Estimated reading: 2 minutes 62 views

When we write a simple program, others can easily understand how the program works. However, if it is a complex and long program, it may not be so easy to understand. If it takes too long, even the people who wrote these programs may not be able to understand the code themselves. Comments make programs easier to read and understand.

Comments are for people who need to read the program, not for the computer to execute, and the computer ignores these comments when running the program.

Python single line comment

In Python, # is a single-line comment character, indicating that the content from # to the end of the line where it is located is comment content, and the program will not execute these comment content.

Let’s annotate the example in the previous section and see the effect. The code is as follows.

while True:
    try:
        firstNumber=int(input("Please enter a non-zero number:"))
        secondNumber=10/firstNumber
        print("No exception occurred")
        break #break out of the while loop
    except ZeroDivisionError: #Determine whether the division is zero
        print ("Incorrect input, 0 cannot be used as a divisor, please try again")
    except ValueError: #Determine whether the input is not a number
        print("Incorrect input, enter a number instead of a character, please try again")

Python multi-line comments

In a Python program, you can also write a multi-line comment, """start with three quotation marks, and end the comment with the next three quotation marks """. The code is as follows.

"""
Function: Demonstrate catching exception
Author: Li Qiang
Date written: July 1, 2019
"""
while True:
    try:
        firstNumber=int(input("Please enter a non-zero number:"))
        secondNumber=10/firstNumber
        print("No exception occurred")
        break #break out of the while loop
    except ZeroDivisionError: #Determine whether the division is zero
        print ("Incorrect input, 0 cannot be used as a divisor, please try again")
    except ValueError: #Determine whether the input is not a number
        print("Incorrect input, enter a number instead of a character, please try again")

Tip: When writing multi-line comments in Python, you can also use 3 single quotes 'instead of 3 double quotes ".

Leave a Comment

CONTENTS