Op 2005-08-19, Donn Cave schreef <[EMAIL PROTECTED]>: > Quoth "Greg McIntyre" <[EMAIL PROTECTED]>: >| I have a Python snippet: >| >| f = open("blah.txt", "r") >| while True: >| c = f.read(1) >| if c == '': break # EOF >| # ... work on c >| >| Is some way to make this code more compact and simple? It's a bit >| spaghetti. > > Actually I'd make it a little less compact -- put the "break" > on its own line -- but in any case this is fine. It's a natural > and ordinary way to express this in Python. > > ... >| But I get a syntax error. >| >| while c = f.read(1): >| ^ >| SyntaxError: invalid syntax >| >| And read() doesn't work that way anyway because it returns '' on EOF >| and '' != False. If I try: > > This is the part I really wanted to respond to. Python managed > without a False for years (and of course without a True), and if > the introduction of this superfluous boolean type really has led > to much of this kind of confusion, then it was a bad idea for sure.
IMO the confusion is the result of True and False appearing late. IMO having python interpret None, '', (), {} and [] as false in a conditional context goes against the spirit of: In the face of ambiguity, refuse the temptation to guess. > The condition that we're looking at here, and this is often the > way to look at conditional expressions in Python, is basically > something vs. nothing. In this and most IO reads, the return > value will be something, until at end of file it's nothing. > Any type of nothing -- '', {}, [], 0, None - will test "false", But '', {}, [] and () are not nothing. They are empty containers. And 0 is not nothing either it is a number. Suppose I have a variable that is either None if I'm not registered and a registration number if I am. In this case 0 should be treated as any other number. Such possibilities, make me shy away from just using 'nothing' as false and writing out my conditionals more explicitly. -- Antoon Pardon -- http://mail.python.org/mailman/listinfo/python-list