First the reason for the failure. Function int
wants either a number or a string that represents an int (from the Python 3 docs). The first part covers your first two examples and the second part covers your third.
However '5.5' isn't a "string that represents an int", hence the failure. It is, of course, a string that represents a number, but that isn't the same thing.
But
int(eval('5.5'))
will return 5 since eval
will return a number that int
will be able to work with.
Now, how to explain it. There are two options (at least). The first (worst) is just to tell the kid that the world isn't magic and int only works for some things, but doesn't handle everything.
But it makes more sense to treat it as an exercise in careful reading of specifications. Read what the specification does say and what it doesn't say. Specifications are meant to be precise.
You can make it a lesson about reading the manual when you get confused, or writing test cases to explore the range of possibilities.
You can make it an lesson about searching for an alternate solution (i.e. eval
) when something you try fails.
You can make it a lesson about "when you are older and get to design things, spend some time getting it right." I haven't explored whether there is logic behind the decision to not include such a case as your fourth example, but I doubt that it was an oversight.
See the note by @ctrl-alt-delor. Function eval
permits the evaluation of arbitrary code, not just simple expressions. It shouldn't be used, for example, with unexamined user input strings. It is safe, however, provided that you have control over the argument in some way.