Pour convertir un entier i en boolean en python il existe la fonction "built-in" bool(). Cette function donne "True" pour tous les entiers sauf pour 0 ou elle donne "False":
>>> bool(0)
False
>>> bool(1)
True
>>> bool(3)
True
>>> bool(-1)
True
Remarque: cette fonction peut aussi être utilisée avec des nombres décimaux:
>>> bool(0.0)
False
>>> bool(1.0)
True
>>> bool(-1.0)
True
>>> bool(7.0)
True
On peut aussi utiliser cette fonction avec une liste, un dictionnaire ou un tuple. Le fonction donne False si il y a aucun elements, sinon True:
>>> bool([])
False
>>> bool([3])
True
>>> bool([0])
True
>>> bool({})
False
>>> bool({'k1':'v1'})
True
>>> bool(())
False
>>> bool(('a','b','c'))
True
References
Liens | Site |
---|---|
bool() | python doc |
Is False == 0 and True == 1 in Python an implementation detail ? | stackoverflow |
What does bool() actually do in python? | stackoverflow |
Python 2.7 quick reference | infohost.nmt.edu |
How to convert a boolean array to an int array | stackoverflow |
Integer to Boolean | stackoverflow |