code review

Steven D'Aprano steve+comp.lang.python at pearwood.info
Mon Jul 2 10:11:16 CEST 2012


On Mon, 02 Jul 2012 12:04:29 +1000, Chris Angelico wrote:

>> Chained comparisons in the Python sense may be rare in computer
>> languages, but it is the standard in mathematics and hardly needs to be
>> explained to anyone over the age of twelve. That is a terrible
>> indictment on the state of programming language design.
> 
> I'd say that proves that Python is a good language for expressing
> mathematics in, then. That's all. 

No. Python is a terrible language for expressing mathematics in. As you 
point out, I can't do things like:

x = y+2
x*3 = y*4+7
print("x = %d, y = %d",x,y)

and sensibly get x = 1, y = -1.


But Python is an excellent language for expressing a series of 
comparisons in, which has applications beyond pure maths or algebra. For 
example:

"c" < first_word < second_word == third_word < "x"

I'm sure I don't have to explain what that means -- that standard chained 
notation for comparisons is obvious and simple. 

In Python, you write it the normal way, as above. But some other 
languages force you into verbosity:

("c" < first_word) and (first_word < second_word) and (second_word == 
third_word) and (third_word < "x")

Worst of all are those languages which allow you to write the expression 
as normal, but evaluate it in a way that you almost never want: the 
maximum number of bugs with the minimum convenience.

This has nothing to do with algebra. It is about picking semantics for 
chained comparisons which is sensible and useful and matches what people 
expect from regular language. 

If you write 2+2 = 2*2 = 4, nearly everyone will agree that, yes, that is 
true. Interpreting it as 1 == 4 is neither sensible nor useful and it is 
certainly not what people expect.


-- 
Steven



More information about the Python-list mailing list