[Python-ideas] for/else syntax

Michael Foord fuzzyman at gmail.com
Fri Oct 2 14:49:07 CEST 2009


2009/10/2 Yuvgoog Greenle <ubershmekel at gmail.com>

> Nonsense - there are several other ways to break out of a loop. Raising an
>> exception or returning for example
>
>
> I do appreciate your response. I'd like you to examine how the "else" in
> question isn't relevant to the discussion of return or raise:
>
> >>> for i in range(10):
> ...     print(1/0)
> ... else:
> ...     print(100)
> ...
> Traceback (most recent call last):
>   File "<stdin>", line 2, in <module>
> ZeroDivisionError: int division or modulo by zero
> >>>
>


The point is that the exception may be handled at an outer level - so the
loop is broken out of and control flow is handed to another part of the
code. Code that *always* raises an exception to break the loop is not common
or interesting, but code that does so under certain circumstances is not
uncommon (raising an exception is one way to break out of nested loops - the
other way is an early return...)




> >>> def eggs():
> ...     for i in range(10):
> ...             return 1234
> ...     else:
> ...             print(69)
> ...
> >>> eggs()
> 1234
> >>>
>
>
The return may be conditional in order to explicitly break out of the loop
under certain circumstances.


Michael
-- 
http://www.ironpythoninaction.com/
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20091002/4627e0ec/attachment.html>


More information about the Python-ideas mailing list