Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

python - How to explain the int() function to a beginner

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.

question from:https://stackoverflow.com/questions/46929622/how-to-explain-the-int-function-to-a-beginner

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...