Python 注釋
注釋可用于解釋 Python 代碼。
注釋可用于提高代碼的可讀性。
在測試代碼時,可以使用注釋來阻止執行。
創建注釋
注釋以 #
開頭,Python 將忽略它們:
實例
#This is a comment print("Hello, World!")
注釋可以放在一行的末尾,Python 將忽略該行的其余部分:
實例
print("Hello, World!") #This is a comment
注釋不必是解釋代碼的文本,它也可以用來阻止 Python 執行代碼:
實例
#print("Hello, World!") print("Cheers, Mate!")
多行注釋
Python 實際上沒有多行注釋的語法。
要添加多行注釋,您可以為每行插入一個 #
:
實例
#This is a comment #written in #more than just one line print("Hello, World!")
或者,以不完全符合預期的方式,您可以使用多行字符串。
由于 Python 將忽略未分配給變量的字符串文字,因此您可以在代碼中添加多行字符串(三引號),并在其中添加注釋:
實例
""" This is a comment written in more than just one line """ print("Hello, World!")
只要字符串未分配給變量,Python 就會讀取代碼,然后忽略它,這樣您就已經完成了多行注釋。