How to explain the int() function to a beginner

In a nutshell: because that’s what the spec says. That’s kind of a useful mindset to get into anyway. 😉

Now, why does the spec say so? There are only a finite number of types a function can accept as valid input. The int function tries to cover two different kinds of use cases:

  1. convert a string representation of an integer into an actual int
  2. cast a float value to an int, truncating it*

The third use case, “convert the string representation of a floating point number to an int is not covered by the spec, because the language designers decided not to cover it. Which seems like a reasonable decision to make, since they needed to draw the line somewhere on what types the function would and wouldn’t accept. The string representation of a floating point number should be parsed by float, not int.

* Actually: any object that has an __int__ method, but lets keep it simple.


As a counter example, in PHP you can try to cast any string to an int, and it will try to give you the best match:

php > echo (int)'3.14';
3
php > echo (float)'3.14';
3.14
php > echo (int)'3 little pigs';
3
php > echo (int)'there are 3 little pigs';
0

Which, quite honestly, is rather insane behaviour, especially that last one. Python has a strict(er) type system; if you’re trying to parse a string as an int, it must be a perfectly valid representation of an integer number, not merely something that somewhere contains something that can be interpreted as a number.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)