Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #63067

Re: Ifs and assignments

From Duncan Booth <duncan.booth@invalid.invalid>
Newsgroups comp.lang.python
Subject Re: Ifs and assignments
Date 2014-01-03 15:46 +0000
Message-ID <XnsA2AAA078A3921duncanbooth@127.0.0.1> (permalink)
References <52C59FF6.5000607@allsup.co> <mailman.4816.1388709915.18130.python-list@python.org> <52c62fa8$0$30001$c3e8da3$5496439d@news.astraweb.com> <mailman.4823.1388720985.18130.python-list@python.org>

Show all headers | View raw


Chris Angelico <rosuav@gmail.com> wrote:

> Maybe a for loop isn't the best other example, but I
> frequently work with places where I want to call some function and
> keep iterating with the result of that until it returns false:
> 
> while (var = func())
> {
>     ....
> }
> 
> In Python, that gets a lot clunkier. The most popular way is to turn
> it into an infinite loop:
> 
> while True:
>     var = func()
>     if not var: break
>     ....
> 

My preferred way would be to write it as a `for` loop:

for var in iter(func, False):
   ...


Though you do have to be sure to get the sentinel value correct as it will 
only break for the expected terminal False, not for 0, "", or None.

-- 
Duncan Booth

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Re: Ifs and assignments Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2014-01-02 19:45 -0500
  Re: Ifs and assignments Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-01-03 14:33 +1100
    Re: Ifs and assignments Chris Angelico <rosuav@gmail.com> - 2014-01-03 14:49 +1100
      Re: Ifs and assignments Roy Smith <roy@panix.com> - 2014-01-02 23:14 -0500
        Re: Ifs and assignments Chris Angelico <rosuav@gmail.com> - 2014-01-03 15:25 +1100
        Re: Ifs and assignments Mark Lawrence <breamoreboy@yahoo.co.uk> - 2014-01-03 04:29 +0000
      Re: Ifs and assignments Duncan Booth <duncan.booth@invalid.invalid> - 2014-01-03 15:46 +0000
    Re: Ifs and assignments Chris Angelico <rosuav@gmail.com> - 2014-01-03 14:55 +1100
      Re: Ifs and assignments Roy Smith <roy@panix.com> - 2014-01-02 23:00 -0500
        Re: Ifs and assignments Chris Angelico <rosuav@gmail.com> - 2014-01-03 15:08 +1100

csiph-web