Hi,

I agree that the behavior of booleans in Python can sometimes lead to subtle 
errors, but I think it's important to stress to students that writing things 
like:

if x>y == True:

is _really_ bad style. After pointing that out, I start taking points away for 
doing this. Code like this shows that the writer really does not understand 
Boolean types and their use. Expressions like this can cause subtle errors in 
just about any language, even those that are statically typed to prevent this 
sort of confusion. In Java, (x>y==true) is not a valid expression, so it won't 
compile. But consider this loop that seems to use done as a boolean flag::

boolean done = false;
while(done = false){
    // do some stuff here
}

The loop body will never execute. This sort of error in a strongly typed 
language is often very hard to spot, since we assume the compiler should catch 
it. If the condition is simply written as:

while(!done){

then you can't go wrong. 

My point is that while I agree this is a "gotcha" in Python, there are similar 
gotchas in just about all languages. The real culprit in the original example 
is poor coding style, not the language semantics per se.

--John

________________________________________
From: edu-sig-bounces+john.zelle=wartburg....@python.org 
[edu-sig-bounces+john.zelle=wartburg....@python.org] on behalf of Christian 
Mascher [christian.masc...@gmx.de]
Sent: Tuesday, March 29, 2011 10:12 AM
To: edu-sig@python.org
Subject: Re: [Edu-sig] Interesting "gotcha"

Hi,

I really like it that python allows me to write

if 10 < x <=  b:
     ...

impossible in many other languages.
But all things come at a cost:

>
>   if x > y == True:
>

I think this is a real gotcha, because it might get you, because you
_know too much_:
 >>> if 4:
        print True


True
 >>>
So all things different from 0, '', ... are considered True by python.
But.....

spoiler ahead ;-)
 >>> 4==True

False
 >>>

Cheers

Christian
_______________________________________________
Edu-sig mailing list
Edu-sig@python.org
http://mail.python.org/mailman/listinfo/edu-sig
_______________________________________________
Edu-sig mailing list
Edu-sig@python.org
http://mail.python.org/mailman/listinfo/edu-sig

Reply via email to