最终等同于Python中的If/Elif语句 [英] 'Finally' equivalent for If/Elif statements in Python

查看:131
本文介绍了最终等同于Python中的If/Elif语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python的if/else语句是否具有与try/except/finally语句类似的finally?可以使我们简化的事情:

Does Python have a finally equivalent for its if/else statements, similar to its try/except/finally statements? Something that would allow us to simplify this:

 if condition1:
      do stuff
      clean up
 elif condition2:
      do stuff
      clean up
 elif condition3:
      do stuff
      clean up
 ...
 ...

对此:

 if condition1:
      do stuff
 elif condition2:
      do stuff
 elif condition3:
      do stuff
 ...
 ...
 finally:
      clean up

仅在满足条件并且其执行任务"运行之后,才会在哪里调用finally?相反,如果不满足任何条件,则不会运行finally代码.

Where finally would only be called only after a condition was met and its 'do stuff' run? Conversely, if no condition was met, the finally code would not be run.

我不喜欢亵渎神灵,但是最好的描述方式是,在导致"finally"的每个行事"块末尾都有一个GOTO语句.

I hate to spout blasphemy, but the best way I can describe it is there being a GOTO statement at the end of each block of 'do stuff' that led to finally.

从本质上讲,它与else语句相反.虽然else仅在不满足其他条件的情况下运行,但只有在满足其他条件的情况下,此命令才会运行.

Essentially, it works as the opposite of an else statement. While else is only run if no other conditions are met, this would be ran ONLY IF another condition was met.

推荐答案

完全可以像这样:

def function(x,y,z):
    if condition1:
        blah
    elif condition2:
        blah2
    else:
        return False

    #finally!
    clean up stuff.

在某些方面,不如您必须使用单独的功能那样方便.但是,优良作法是不要做太长的功能.将您的逻辑分成易于阅读的小功能(通常最多1页长),可以使测试,记录文档和理解执行流程变得更加容易.

In some ways, not as convenient, as you have to use a separate function. However, good practice to not make too long functions anyway. Separating your logic into small easily readable (usually maximum 1 page long) functions makes testing, documenting, and understanding the flow of execution a lot easier.

要注意的一件事是,finally子句在发生异常时不会运行.为此,您还需要在其中添加try:内容.

One thing to be aware of is that the finally clause will not get run in event of an exception. To do that as well, you need to add try: stuff in there as well.

这篇关于最终等同于Python中的If/Elif语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆