Rules for If-Statements
- Every if-statement must have an else.
- 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.
- Never nest if-statements more than two deep and always try to do them one deep.
- Treat if-statements like paragraphs, where each if-elif-else grouping is like a set of sentences. Put blank lines before and after.
- 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.
- 每一個if語句必須包含一個else
- 如果這個else永遠不應該被執行到,因爲其本身無意義,那麼你必須在else之後使用一個die函數,打印出錯誤信息並“死”給你看,這樣你可以找到很多的錯誤。
- if語句的嵌套不要超過2層,最好保持只有一層,這意味着,如果在if裏面又有一個if,那你就需要把第二個if移到另一個函數裏面。
- 使用if elif else要注意縮進(Python中是強制縮進的)
- 你的布爾測試應該很簡單,如果他們很複雜,你需要將他們的運算事先放到一個變量裏,並且爲變量取一個好名字(有意義的名字,能直接看出變量所指)