Counterintuitive behaviour of int() in python

后端 未结 4 1423
故里飘歌
故里飘歌 2021-02-04 23:07

It\'s clearly stated in the docs that int(number) is a flooring type conversion:

int(1.23)
1

and int(string) returns an int if and only if the

4条回答
  •  鱼传尺愫
    2021-02-04 23:35

    In simple words - they're not the same function.

    • int( decimal ) behaves as 'floor i.e. knock off the decimal portion and return as int'
    • int( string ) behaves as 'this text describes an integer, convert it and return as int'.

    They are 2 different functions with the same name that return an integer but they are different functions.

    'int' is short and easy to remember and its meaning applied to each type is intuitive to most programmers which is why they chose it.

    There's no implication they are providing the same or combined functionality, they simply have the same name and return the same type. They could as easily be called 'floorDecimalAsInt' and 'convertStringToInt', but they went for 'int' because it's easy to remember, (99%) intuitive and confusion would rarely occur.

    Parsing text as an Integer for text which included a decimal point such as "4.5" would throw an error in majority of computer languages and be expected to throw an error by majority of programmers, since the text-value does not represent an integer and implies they are providing erroneous data

提交回复
热议问题