When does Python perform type conversion when comparing int and float?

前端 未结 7 1423
太阳男子
太阳男子 2021-01-12 23:22

Why does Python return True when I compare int and float objects which have the same value?

For example:

>&         


        
7条回答
  •  悲哀的现实
    2021-01-13 00:22

    The simple answer is that the langue is designed this way. Here is an excerpt from the documentation supporting this:

    6.10.1 Value Comparisons

    Numbers of built-in numeric types (Numeric Types — int, float, complex) and of the standard library types fractions.Fraction and decimal.Decimal can be compared within and across their types, with the restriction that complex numbers do not support order comparison.

    In other words, we want different numeric types with the same value to be equal.

    PEP 20

    Special cases aren't special enough to break the rules.

    Although practicality beats purity.

    What benefit is there to making numeric types not comparable, besides making life difficult in most common cases?

提交回复
热议问题