Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it guaranteed that False "is 0" and True "is 1"? [duplicate]

Tags:

python

boolean

Possible Duplicate:
Is False == 0 and True == 1 in Python an implementation detail or is it guaranteed by the language?

I noticed today that the following works using python 2.6 (Cpython)...

>>> a=[100,200]
>>> a[True]
200
>>> a[False]
100

Is this portable to other python implementations (e.g. is True/False guaranteed to inherit from int? Is True guaranteed to evaluate to 1 instead of some other non-zero number?) Is there any situation where this would be useful? It seems like it could be used as another form of a ternary operator, but I don't know how much is gained there...

like image 489
mgilson Avatar asked Apr 21 '12 23:04

mgilson


People also ask

Does 1 equal True or False?

1 is considered to be true because it is non-zero. The fourth expression assigns a value of 0 to i. 0 is considered to be false.

Is 0 or 1 true or False in C?

C does not have boolean data types, and normally uses integers for boolean testing. Zero is used to represent false, and One is used to represent true. For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true.

Is bool always 0 or 1?

Boolean values and operations C++ is different from Java in that type bool is actually equivalent to type int. Constant true is 1 and constant false is 0. It is considered good practice, though, to write true and false in your program for boolean values rather than 1 and 0.

Why is 1 true and 0 False Python?

The Python Boolean type is one of Python's built-in data types. It's used to represent the truth value of an expression. For example, the expression 1 <= 2 is True , while the expression 0 == 1 is False . Understanding how Python Boolean values behave is important to programming well in Python.


1 Answers

It is part of the language specification, so any Python implementation should implement the booleans as equivalent to the integers.

Booleans

These represent the truth values False and True. The two objects representing the values False and True are the only Boolean objects. The Boolean type is a subtype of plain integers, and Boolean values behave like the values 0 and 1, respectively, in almost all contexts, the exception being that when converted to a string, the strings "False" or "True" are returned, respectively.

like image 181
Ignacio Vazquez-Abrams Avatar answered Oct 01 '22 19:10

Ignacio Vazquez-Abrams