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. 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", and everything else is "true". Of course True is true too, and False is false, but as far as I know they're never really needed. You are no doubt wondering when I'm going to get to the part where you can exploit this to save you those 3 lines of code. Sorry, it won't help with that. | Is this related to Python's expression vs. statement syntactic | separation? How can I be write this code more nicely? Yes, exactly. Don't worry, it's nice as can be. If this is the worst problem in your code, you're far better off than most of us. Donn Cave, [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list