Python Idiom Question

David Bolen db3l at
Tue Jul 10 19:09:02 EDT 2001

James Logajan <JamesL at Lugoj.Com> writes:

> Tim Daneliuk wrote:
> > 
> > What is the equivalent python idiom to the following 'C' code:
> > 
> > while (x=getchar() != 'N')
> >         {
> >         Do something}
> > 
> > In other words, is there a convenient way to simultaneously get
> > input, from say, raw_input() or, and check the return
> > value agains some logical construct, re pattern match, or whatever?
> What is wrong with:
> while 1:
> 	x=raw_input()
> 	if x == 'N': break
> 	Do something

Note that this isn't quite a precise match.  getchar() will only
return a single character from stdin, although depending on
environment a full line may be buffered and the user has to hit Enter
before the application sees it - and if so, the application will see
the newline.  Then, subsequent iterations on getchar() will return
anything else that was entered on that line.  It's also an int return
with EOF (-1) on end of file.

On the other hand, raw_input() will return an entire line as a string
(but sans trailing newline) and will raise an exception on EOF.

I think the closest match is probably more along the lines of:

    import sys

    while 1:
	x =
	if x == 'N': break
	Do something

Note that both the original example and this will loop on EOF, which
probably isn't what is desired, but would need to be fixed in either
of the cases (e.g., in the Python case also breaking out if x was '').

-- David
 \               David Bolen            \   E-mail: db3l at  /
  |             FitLinxx, Inc.            \  Phone: (203) 708-5192    |
 /  860 Canal Street, Stamford, CT  06902   \  Fax: (203) 316-5150     \

More information about the Python-list mailing list