First python program, syntax error in while loop

Roy Smith roy at panix.com
Mon May 6 09:08:44 EDT 2013


In article <mailman.1360.1367843880.3114.python-list at python.org>,
 Mark Lawrence <breamoreboy at yahoo.co.uk> wrote:

> > while (number != guess) and (tries < 5):
> 
> One of these days I'll work out why some people insist on using 
> superfluous parentheses in Python code.  Could it be that they enjoy 
> exercising their fingers by reaching for the shift key in conjunction 
> with the 9 or 0 key?

There's lots of reasons.  Some valid, some not.

Lets dispense with the invalid reason first.  They've come from 
C/C++/Java/whatever and are used to typing parens around the conditions 
for if/for/while statements.  To them, I say, "Stop trying to write 
FORTRAN code in languages that aren't FORTRAN".

In this case, however, I have no problem with the extra parens.  Look at 
these two statements:

>> while (number != guess) and (tries < 5):
>> while number != guess and tries < 5:

They have the same meaning.  To correctly interpret the second one, you 
need to know that != and < bind tighter than "and". One could say that 
you should know that, and maybe you would be right.

On the other hand, I've long since given up trying to remember operator 
precedence in various languages.  If I ever have even the slightest 
doubt, I just go ahead and put in the extra parens.  It takes another 
few ms to type, and it removes all ambiguity (for both me, and every 
future person who has to read my code).  And, every once in a while, it 
keeps me from writing a subtle and hard-to-find bug because the 
precedence rules I was sure I had remembered correctly turned out to be 
wrong for the language I happened to be typing that day.

BTW, in C, I used to write:

return (foo)

for years until somebody pointed out to me that

return foo

works.  I just assumed that if I had to write:

if (foo)
while (foo)
for (foo; bar; baz)

then

return (foo)

made sense too.



More information about the Python-list mailing list