[Discuss] A question for the Python gurus
Deryk Barker
dbarker at camosun.bc.ca
Fri Jul 28 22:54:05 PDT 2006
Adam Parkin wrote:
..........
> Well, the actual problem I was working on that lead me to ask was
> reading from stdin. I just think this code looks wrong/ugly to me:
>
> while (1):
> line = sys.stdin.readline()
> if (not line):
> break
>
> # now do something with line
>
> I'd rather have something that looked like:
>
> while (line = sys.stdin.readline())
> # do something with line
Ah, I blame C for this.
the structurally correct way is:
line = sys.stdin.readline ()
while line:
# do something with line
line = sys.stdin.readline ()
it's what Michael Jackson (no, not that one) calls the read ahead and
ensures that you only enter the loop body when there is indeed something
to do.
It's only one line longer and will make the function call the same
number of times, but it's clearer by far - clearer IMHO than the C-style
while (line = ...) which I have never liked.
More information about the Discuss
mailing list