python中 if-else 与 try-except的转换 while 与 whileTrue-try-except的转换

if-else 与 try-except转换 while 与 while-True-try-except转换

比较神奇的写法,直接看代码吧
见如下if-else场景

if fun():
    do something1
else:
    do something2

如果fun()抛出异常表示假,那么可以改写成如下形式

try:
    fun()
    do something1
expect:
    do something2

类似的while场景

while fun():
    do something

如果fun()抛出异常表示假,那么可以改写成如下形式

while True:
    try:
        fun()
        break
    expect:
        do something

以上是我在写爬虫的时候碰到的情况,意外发现这种改写能使程序更加有效率,鲁棒性更强。

你可能感兴趣的:(python,爬虫)