Using try vs if in python

后端 未结 9 1038
终归单人心
终归单人心 2020-11-22 12:59

Is there a rationale to decide which one of try or if constructs to use, when testing variable to have a value?

For example, there is a f

9条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 13:24

    Please ignore my solution if the code I provide is not obvious at first glance and you have to read the explanation after the code sample.

    Can I assume that the "no value returned" means the return value is None? If yes, or if the "no value" is False boolean-wise, you can do the following, since your code essentially treats "no value" as "do not iterate":

    for r in function() or ():
        # process items
    

    If function() returns something that's not True, you iterate over the empty tuple, i.e. you don't run any iterations. This is essentially LBYL.

提交回复
热议问题