python if elif else_最好的做法是在Python if或if / elif语句的末尾包含else:pass语句吗?...

1586010002-jmsa.png

If I write:

if a == b:

# do something

elif a == c:

# do something else

and I just want to pass otherwise, is writing out the following required at the end?:

else:

pass

It seems to run fine without the else: statement in the interpreter, is there a reason I'm not aware of that I should always include else: pass in these cases?

解决方案

No, it isn't, the else suite is entirely optional.

if_stmt ::= "if" expression ":" suite

( "elif" expression ":" suite )*

["else" ":" suite]

where (...)* means zero or more, and [...] means optional. So a valid if compound statement has an if line and suite, 0 or more elif lines and corresponding suites, and at most one else line and suite, which is optional.

The Python compiler will ignore any else: pass block, there is really no point in including it:

>>> import dis

>>> dis.dis(compile('''\

... if True:

... foo

... else:

... pass

... ''', '', 'exec'))

1 0 LOAD_NAME 0 (True)

3 POP_JUMP_IF_FALSE 13

2 6 LOAD_NAME 1 (foo)

9 POP_TOP

10 JUMP_FORWARD 0 (to 13)

4 >> 13 LOAD_CONST 0 (None)

16 RETURN_VALUE

>>> dis.dis(compile('''\

... if True:

... foo

... ''', '', 'exec'))

1 0 LOAD_NAME 0 (True)

3 POP_JUMP_IF_FALSE 13

2 6 LOAD_NAME 1 (foo)

9 POP_TOP

10 JUMP_FORWARD 0 (to 13)

>> 13 LOAD_CONST 0 (None)

16 RETURN_VALUE

where the only difference is the line number attached to the LOAD_CONST bytecode because of the extra lines in the first source sample.

Stylistically, else: pass is just clutter, something to reduce readability.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值