Assignment and comparison in one statement
William McBrine
wmcbrine at users.sf.net
Sat May 24 20:36:28 EDT 2008
On Sat, 24 May 2008 13:12:13 +0200, Johannes Bauer wrote:
> char *tmp;
> tmp = fgets(buf, sizeof(buf), f);
> while (tmp) {
> printf("%s\n", buf);
> tmp = fgets(buf, sizeof(buf), f);
> }
I think a more Pythonic way to write this, in general, would be:
while (1) {
char *tmp = fgets(buf, sizeof(buf), f);
if (!tmp)
break;
printf("%s\n", buf);
}
In actual Python, that's:
while True:
buf = f.readline()
if not buf:
break
print buf
Yeah, it's longer than the traditional C way, but you don't need to have
duplicate fgets() (or whatever) lines. On the plus side, you're less
likely to get '=' and '==' accidentally swapped in Python.
For this specific example, it can be cut down much more:
for buf in f.readlines():
print buf
(BTW, all of the above result in doublespacing the original file, but
that's what your C version was doing, so I kept it that way.)
--
09 F9 11 02 9D 74 E3 5B D8 41 56 C5 63 56 88 C0 -- pass it on
More information about the Python-list
mailing list