1. 程式人生 > 實用技巧 >Python程式設計:Python之禪及註釋

Python程式設計:Python之禪及註釋

Python之禪

程式語言Perl曾在網際網路領域長期佔據著統治地位, 早期的大多數互動式網站使用的都是Perl指令碼。彼時,解決問題的辦法有多個Perl社群奉為座右銘。這種理念一度深受大家的喜愛,因為這種語言固有的靈活性使得大多數問題都有很多不同的解決之道。在開發專案期間,這種靈活性是可以接受的,但大家最終認識到,過於強調靈活性會導致大型專案難以維護:要通過研究程式碼搞清楚當時解決複雜問題的人是怎麼想的,既困難又麻煩,還會耗費大量的時間。經驗豐富的程式設計師倡導儘可能避繁就簡。Python社群的理念都包含在TimPeters撰寫的“Python之禪

Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 23:11:46) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import this
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex 
is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one
-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!

網上的解釋非常多,自己翻譯了一下

美麗勝於醜陋。
顯式勝於隱式。
簡單勝於複雜。
複雜勝於繁雜。
扁平比巢狀更好。
稀疏勝於密集。
可讀性很重要。
特殊情況不足以違反規則。
儘管實用性勝過純度。
錯誤絕不能默默傳遞。
除非明確地保持沉默。
面對模稜兩可的想法,拒絕猜測的誘惑。
應該有一種,且最好只有一種,顯而易見的方法。
當然這是沒法一蹴而就的,除非你是荷蘭人。(這裡的荷蘭人指Python的作者Guido van Rossum)
固然,立刻著手 好過 永遠不做。
然而,永遠不做 也好過 不審慎思考一擼袖子就莽著幹
如果實現難以解釋,那是個壞主意。
如果實現易於解釋,則可能是個好主意。
名稱空間是一個很棒的主意,讓我們做更多這些吧!

註釋

每個語言都有註釋,註釋的作用是為了幫助開發人員更好的閱讀程式碼。

在Python中,註釋分為兩種,一種是單行註釋(#)

print('a')
#print('b')
print('c')

輸出
a
c

一種是多行註釋('''''')("""""")六個單引號或六個雙引號

'''
這是
六個單引號的註釋
'''

"""
這是
六個雙引號的註釋
"""