[英]Python: correct usage of triple quotes
如果我在 else 語句之前使用三引號,我的代碼不會運行:
def do_something(test_option=False):
"""
function to do something
:param test_option: bool
:return: None
"""
'''
Testing
'''
if test_option==True:
print("testing")
'''
Visualization
'''
else:
# do thing
我的else
下有一個紅色的波浪線。 為什么是這樣?
我知道 ''' 也可以用於函數注釋。 它不應該在其他任何地方使用嗎?
關於突出代碼組織的替代方法的建議? (我的 IDE 從字面上用黃色突出顯示 ''',我一直在使用它來組織我的代碼的不同部分。)
三引號表示字符串文字,而不是注釋,因此通過將Visualization
放置在具有相同縮進級別的if
塊之外,您實際上是在結束if
語句,因此下面的else
子句變得無效。 在if
塊內縮進Visualization
以避免此類錯誤。
問題是 Python 認為您已經結束了 if 語句。 您退回了縮進以放入您的評論,因此它的語法無效。 嘗試這個:
def do_something(test_option=False):
"""
function to do something
:param test_option: bool
:return: None
"""
'''
Testing
'''
if test_option==True:
print("testing")
'''
Visualization
'''
else:
# do thing
pass
僅對文檔字符串使用三重引號(或其他很少見的多行字符串)。
不要試圖將它們用於評論。 使用# your comment goes here...
def do_something(test_option=False):
"""
function to do something
:param test_option: bool
:return: None
"""
# Testing
if test_option==True:
print("testing")
# Visualization
else:
# do thing
(順便注意注釋更緊湊)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.