Behavior of the for-else construct

Rob Cliffe rob.cliffe at btinternet.com
Fri Mar 4 17:22:30 EST 2022



On 04/03/2022 20:52, Avi Gross via Python-list wrote:
>
> I have an observation about exception handling in general. Some people use exceptions, including ones they create and throw, for a similar idea. You might for example try to use an exception if your first attempt fails that specifies trying the next attempt. In my example of the PATH variable, you might use something like calling a function and giving it what you are looking for as well as a local copy of the PATH variable content and the exception would be to call the function again with the first component of PATH removed until you fail with an empty PATH. Yes, this is similar to just having a recursive function.
That sounds neither readable nor efficient compared with using split() 
plus a loop.  Maybe you mean this to be a toy, unrealistic example?
> So the example tossed at us looks a bit more like this and it does run the ELSE not because the loop is not done but because  the loop never calls a break:
>
> for x in range(0):
>    print(x)
> else:
>    print("Finally finished!")
This would be more readable with a `zeroiterations` keyword, which 
accurately describes both the semantics and the intent.
> Which leads me right back to wondering why the sentinel approach is so bad!
>
>
It's not that bad, but it's more convenient and readable if it can be 
avoided.
Best wishes
Rob Cliffe


More information about the Python-list mailing list