【Python】if語句使用規則

Rules for If-Statements

  1. Every if-statement must have an else.
  2. If this else should never run because it doesn't make sense, then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors.
  3. Never nest if-statements more than two deep and always try to do them one deep.
  4. Treat if-statements like paragraphs, where each if-elif-else grouping is like a set of sentences. Put blank lines before and after.
  5. Your boolean tests should be simple. If they are complex, move their calculations to variables earlier in your function and use a good name for the variable.

If you follow these simple rules, you will start writing better code than most programmers. 

  1. 每一個if語句必須包含一個else
  2. 如果這個else永遠不應該被執行到,因爲其本身無意義,那麼你必須在else之後使用一個die函數,打印出錯誤信息並“死”給你看,這樣你可以找到很多的錯誤。
  3. if語句的嵌套不要超過2層,最好保持只有一層,這意味着,如果在if裏面又有一個if,那你就需要把第二個if移到另一個函數裏面。
  4. 使用if elif else要注意縮進(Python中是強制縮進的)
  5. 你的布爾測試應該很簡單,如果他們很複雜,你需要將他們的運算事先放到一個變量裏,並且爲變量取一個好名字(有意義的名字,能直接看出變量所指)
如果你遵循上面的原則,你就會寫出比大部分程序員都好的代碼來。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章