【Python】if語句使用規則
阿新 • • 發佈:2019-02-08
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
- 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中是強制縮排的)
- 你的布林測試應該很簡單,如果他們很複雜,你需要將他們的運算事先放到一個變數裡,並且為變數取一個好名字(有意義的名字,能直接看出變數所指)