Simple if-else question

John Yeung gallium.arsenide at gmail.com
Wed Sep 30 01:31:26 EDT 2009


On Sep 29, 1:25 pm, MRAB <pyt... at mrabarnett.plus.com> wrote:

> The example that makes it clearest for me is searching
> through a list for a certain item and breaking out of
> the 'for' loop if I find it. If I get to the end of the
> list and still haven't broken out then I haven't found
> the item, and that's when the else statement takes effect:
>
> for item in my_list:
>      if item == desired_item:
>          print "Found it!"
>          break
> else:
>      print "It's not in the list"

To me, this is the quintessential use case and clearest example of the
for-else.

John



More information about the Python-list mailing list