Convertir un entier en boolean sous python


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

Creative Commons License

To the extent possible under law, the person who associated CC0 with this work has waived all copyright and related or neighboringrights to this work.