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中是强制缩进的)
- 你的布尔测试应该很简单,如果他们很复杂,你需要将他们的运算事先放到一个变量里,并且为变量取一个好名字(有意义的名字,能直接看出变量所指)
如果你遵循上面的原则,你就会写出比大部分程序员都好的代码来。