Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Finally' equivalent for If/Elif statements in Python

Tags:

python

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
 ...
 ...

to this:

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

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.

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.

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.

like image 879
nobillygreen Avatar asked Feb 06 '14 20:02

nobillygreen


People also ask

What is alternative of if Elif else Python?

Switch Case is a cleaner and faster alternative to if-else conditions in your code. Python does not directly support Switch Case but it does provide some very useful and efficient workarounds.

Can you end an if statement with Elif Python?

Essentially, yes. elif True would work like else in this case.

How do you end an Elif in Python?

To end the block, decrease the indentation. Subsequent statements after the block will be executed out of the if condition.

What is if Elif statement in Python?

If-elif-else statement is used in Python for decision-making i.e the program will evaluate test expression and will execute the remaining statements only if the given test expression turns out to be true. This allows validation for multiple expressions.


2 Answers

It can be done totally non-hackily like this:

def function(x,y,z):     if condition1:         blah     elif condition2:         blah2     else:         return False      #finally!     clean up stuff. 

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.

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.

like image 133
Daniel Fairhead Avatar answered Sep 30 '22 18:09

Daniel Fairhead


you can use try

try:
    if-elif-else stuff
finally:
    cleanup stuff

the exception is raised but the cleanup is done

like image 22
Durgeoble Avatar answered Sep 30 '22 18:09

Durgeoble