How to explain the int() function to a beginner

Question:

I am tutoring a neighbour’s child and we were exploring the int() function before using it with input() – which returns a string. We tried the following:

int(5)
int(5.5)
int('5')
int('5.5')

The first three returned 5 as expected; the last one threw the error

ValueError: invalid literal for int() with base 10: ‘5.5’

Given the behaviour of the first three lines how do I explain the error to a 14-year old (background = speaks 4 languages but maths is not so hot)?

UPDATE
C# exhibits the same behaviour:
Convert.ToInt32("5.5"); throws the error

Input string was not in a correct format.

Asked By: Peter Smith

||

Answers:

The problem with that line is that there are two conversions involved:

"5.5" (string) -> 5.5 (float) -> 5 (int)

The conversion operators in Python will only apply one conversion at a time, never two chained, because that could become confusing in many cases.

The solution is to apply two nested conversions:

int(float("5.5"))
Answered By: rodrigo

You could refer to docs:

class int(x=0)
class int(x, base=10)

Return an integer object constructed from a number or string x, or return 0 if no arguments are given. If x is a number, return
x.__int__(). For floating point numbers, this truncates towards zero.

If x is not a number or if base is given, then x must be a string, bytes, or bytearray instance representing an integer literal in radix
base.
Optionally, the literal can be preceded by + or – (with no space
in between) and surrounded by whitespace. A base-n literal consists of
the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35.
The default base is 10. The allowed values are 0 and 2–36. Base-2, -8,
and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or
0x/0X, as with integer literals in code. Base 0 means to interpret
exactly as a code literal, so that the actual base is 2, 8, 10, or 16,
and so that int(‘010’, 0) is not legal, while int(‘010’) is, as well
as int(‘010’, 8).

The integer type is described in Numeric Types — int, float, complex.

(emphasis mine)

Referring to docs teaches that in programming nothing is really arbitrary, and compilers/interpreters are simply following rules.

I would say that the problem behind this is operator overloading, because there are really two int() functions involved: one that converts a string (if possible), the other truncates floats. If the kid understands types, I think she/he will also understand what overloading is.

Answered By: Peter Leupold

I think I would go about it by saying that both int(5.5) and int('5.5') are not what you are Supposed To Do. rodrigo’s answer gives an explanation why one still works, but when explaining things to a child I would try to keep things as explicit as possible, and implicit conversions don’t help with that.

So, while overly explicit, why not teach to go like this:

int(floor(float('5.5')))

At least then everything is perfectly clear and obvious.

Answered By: Arne

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.

Answered By: deceze

Try explaining strings containing digits as if it was written out as words.

int(5)
int(5.5)

works since Python’s int() function “sees” it as numbers and takes the whole-number-part, like another child, that doesn’t know anything about floating point / decimal places -> both would be interpreted as 5, the rest is ignored.

Now: using strings

int('5')
int('5.5')

could be interpreted as either “five” which Python’s int() function knows how to translate to 5, but a verbal “fivepointfive” is not what our child has ever heard, not knowing anything about floating point. (int() function being the child here)

A nice question and an usual challenge to try explain it this way.

Answered By: EvilSmurf

Your (imaginary) function takes a picture of a cat as a parameter and you tried to pass it an actual cat. There’s a conversion that needs to happen first from cat to picture of cat before the function knows what to do with it.

Answered By: JeffC
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.