Counterintuitive behaviour of int() in python

后端 未结 4 1416
故里飘歌
故里飘歌 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:37

    There is no special reason. Python is simply applying its general principle of not performing implicit conversions, which are well-known causes of problems, particularly for newcomers, in languages such as Perl and Javascript.

    int(some_string) is an explicit request to convert a string to integer format; the rules for this conversion specify that the string must contain a valid integer literal representation. int(float) is an explicit request to convert a float to an integer; the rules for this conversion specify that the float's fractional portion will be truncated.

    In order for int("3.1459") to return 3 the interpreter would have to implicitly convert the string to a float. Since Python doesn't support implicit conversions, it chooses to raise an exception instead.

提交回复
热议问题