Simple if-else question

Olof Bjarnason olof.bjarnason at gmail.com
Thu Oct 1 06:00:36 EDT 2009


2009/10/1 Sion Arrowsmith <sion at viridian.paintbox>:
> MRAB  <python at mrabarnett.plus.com> wrote:
>>> [ for ... else ]
>>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:
>
> What works for me is thinking about the while ... else construct
> and comparing it to if ... else:
>
> if x:
>    print "x is True"
> else:
>    print "x is False"
>
> while x:
>    print "x is True"
>    x -= 1 # or something
>    # A break here exits the loop with x True
> else:
>    print "x is False"
>
> then the step from while to for is obvious.

Am I grokking for..else:

for i in range(10):
  if fn(i):
    break
nobreak:  # let 'nobreak' mean 'else'
  print('break did not happen')

>
> --
> \S
>
>   under construction
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
twitter.com/olofb
olofb.wordpress.com
olofb.wordpress.com/tag/english



More information about the Python-list mailing list