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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值