On Sat, 28 Apr 2007 14:33:23 +0200, Szabolcs wrote:

> Newbie question:
> 
> Why is 1 == True and 2 == True (even though 1 != 2),
> but 'x' != True (even though  if 'x':  works)?

Everything in Python has a truth-value. So you can always do this:

if some_object:
    print "if clause is true"
else:
    print "else clause"

no matter what some_object is.

The constants True and False are a pair of values of a special type bool.
The bool type is in fact a sub-class of int:

>>> issubclass(bool, int)
True
>>> 7 + False
7
>>> 7 + True
8

Can you guess what values True and False are "under the hood"?

>>> 1 == True
True
>>> 0 == False
True
>>> 2 == True
False
>>> if 2:
...     print "2 is considered true"
...
2 is considered true


If you are getting different results, the chances are that you have
accidentally reassigned that names True or False:

>>> True = 2  # DON'T DO THIS!!!
>>> 2 == True
True



-- 
Steven.

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to