|
Original |
Translation |
|
37
|
while True: line = f.readline() if not line: break ... # do something with line
|
|
|
38
|
The reason for not allowing assignment in Python expressions is a common, hard-to-find bug in those other languages, caused by this construct:
|
|
|
39
|
if (x = 0) { // error handling } else { // code that only works for nonzero x }
|
|
|
40
|
The error is a simple typo: ``x = 0``, which assigns 0 to the variable ``x``, was written while the comparison ``x == 0`` is certainly what was intended.
|
|
|
41
|
|
42
|
An interesting phenomenon is that most experienced Python programmers recognize the ``while True`` idiom and don't seem to be missing the assignment in expression construct much; it's only newcomers who express a strong desire to add this to the language.
|
|
|
43
|
There's an alternative way of spelling this that seems attractive but is generally less robust than the "while True" solution::
|
|
|
44
|
line = f.readline() while line: ... # do something with line... line = f.readline()
|
|
|
45
|
The problem with this is that if you change your mind about exactly how you get the next line (e.g. you want to change it into ``sys.stdin.readline()``) you have to remember to change two places in your program -- the second occurrence is hidden at the bottom of the loop.
|
|
|
46
|
The best approach is to use iterators, making it possible to loop through objects using the ``for`` statement. For example, in the current version of Python file objects support the iterator protocol, so you can now write simply::
|
|