【Python】if语句使用规则
2015-10-11 21:45
706 查看
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中是强制缩进的)
你的布尔测试应该很简单,如果他们很复杂,你需要将他们的运算事先放到一个变量里,并且为变量取一个好名字(有意义的名字,能直接看出变量所指)
如果你遵循上面的原则,你就会写出比大部分程序员都好的代码来。
相关文章推荐
- 【Python】Learn Python the hard way, ex35 通过一个简单游戏,练习循环和分支语句
- Python运维编程
- 【Python之旅】第六篇(四):Python多线程锁
- 【Python之旅】第六篇(四):Python多线程锁
- python中的矩阵运算
- 【Python】Learn Python the hard way, ex33 while循环
- 【Python】Learn Python the hard way, ex32 for循环
- 【Python】Learn Python the hard way, ex29 if语句
- 【Python之旅】第六篇(三):Python多线程及其使用方法
- 【Python】Learn Python the hard way, ex26 修改代码错误
- ubuntu下手动安装python源码
- Python源码剖析笔记7-类机制
- 【Python】Learn Python the hard way, ex25 函数综合练习
- python.time
- python中魔法属性和魔法方法
- Python魔法方法指南
- 【Python】Learn Python the hard way, ex24 函数综合练习
- leetcode之Largest Number
- PYTHON getattr setattr hasattr delattr内置函数
- 【Python】Learn Python the hard way, ex21 函数返回值return