Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract boolean from float in python [duplicate]

Tags:

python

Anyways when debuging my code I found statement that basically subtracted boolean from float.

Then I tried following in python console:

>>> 15.0 - True 
14.0
>>> 15.0 - False
15.0

Can anyone explain to me:

  • Why subtracting booleans from numeric types is legal (the docs only state that you can do and, not and or on boolean values: http://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not)
  • Has this any practical use?
like image 686
jb. Avatar asked Dec 15 '22 06:12

jb.


1 Answers

It is legal, because bool is a subclass of int:

>>> bool.__bases__
(<type 'int'>,)
>>> True == 1
True
>>> False == 0
True

Yes, it has some practical application. For example it was possible to do something like that before ternary statement was introduced:

result = [value_if_false, value_if_true][condition]

Which basically does what would be done in this code:

if condition:
    result = value_if_false
else:
    result = value_if_true

Other practical usages are:

  • you can sum several checks / booleans to receive number of results equaling True,
  • you can multiply by the result of the check:

    result = can_count_a * a + can_count_b * b
    
like image 125
Tadeck Avatar answered Dec 17 '22 21:12

Tadeck