<p>First the reason for the failure. Function <code>int</code> 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. </p>

<p>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. </p>

<p>But</p>

<pre><code>int(eval('5.5'))
</code></pre>

<p>will return 5 since <code>eval</code> will return a number that <code>int</code> will be able to work with. </p>

<p>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. </p>

<p>But it makes more sense to treat it as an exercise in careful reading of specifications. Read what the specification <em>does</em> say and what it <em>doesn't</em> say. Specifications are meant to be precise. </p>

<p>You can make it a lesson about reading the manual when you get confused, or writing test cases to explore the range of possibilities. </p>

<p>You can make it an lesson about searching for an alternate solution (i.e. <code>eval</code>) when something you try fails. </p>

<p>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. </p>

<hr>

<p>See the note by @ctrl-alt-delor. Function <code>eval</code> permits the evaluation of arbitrary <em>code</em>, 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. </p>

CC BY-SA 3.0
2017-10-26T13:09:41.270Z
`int(eval(aString))` is very dangerous if `aString` comes from user input. It will allow the user to execute arbitrary code.
ctrl-alt-delor
CC BY-SA 3.0
2017-10-26T13:14:19.137Z
Excellent point. eval is a very big hammer.
Buffy
CC BY-SA 3.0
2017-10-31T00:33:05.080Z
I think this might also be well coupled with a lesson on "writing good specifications is hard."  You don't really get a sense for just how hard it is until many years into programming, but you can at least explain that spec writers have to make tradeoffs.  This might be well coupled with ctrl-alt-delor's example of `int("36/5")`, which starts to show how hard it can be to draw the line on functionality.
Cort Ammon
CC BY-SA 3.0
2017-10-26T11:46:12.667Z
2017-10-26T13:26:49.120Z
2017-10-26T13:26:49.120Z
Buffy
<p>I agree with @Buffy, but also.</p>

<ul>
<li><code>int(42)</code> <code>"42" → 42</code> is one step: it converts string to int or throws.</li>
<li><code>int(7.2)</code> <code>7.2 → 7</code> is one step: it converts float/real to int (and rounds).</li>
<li><code>int("7.2")</code> <code>"7.2" → 7.2 → 7</code>✗ is two steps: convert string to float, and float to int.</li>
<li><code>int("36/5")</code> What about this? Should it be able to do this.</li>
</ul>

<p>The problem that is causing the confusion is that we have effectively two functions. <code>int</code> taking a string, and <code>int</code> taking a float. They both do different things.</p>

CC BY-SA 3.0
2017-10-27T15:26:57.833Z
@EllenSpertus, thanks I have now fixed the answer. It is now 42.
ctrl-alt-delor
CC BY-SA 3.0
2017-10-28T18:31:28.600Z
As I said below, type determines context.  This is an example of function overloading, which is covert in duck-typed Python and overt in statically typed C++ and Java.
ncmathsadist
CC BY-SA 3.0
2017-10-26T13:24:02.713Z
2017-10-27T15:26:17.097Z
2017-10-27T15:26:17.097Z
ctrl-alt-delor
<p>It is important to discuss the type system early, as it is the whole basis upon which objects interact.  The type system is the species structure of the Python object ecosystem.</p>

<p>Strings interact with string behaviors: + is concatenation, [] is substringing, and *(string,int) causes repetition.</p>

<p>Numbers, in the presence of arithmetic operators, do arithmetic.  </p>

<p>The moral: type determines context and therefore regulates the interactions between objects.  </p>

<p>The <code>int()</code> cast expects an object that is convertible into an integer.  If it is passed a floating point number, it truncates the number towards zero.  If it is passed a numerical string containing a valid parseable number, it extracts the number value from the string.  If it is passed a boolean, it converts <code>true</code> to 1 and <code>false</code> to 0.  </p>

<p>If it is passed something that is not a parseable into a number, it throws a <code>ValueError</code>.  </p>

CC BY-SA 3.0
2017-10-27T15:13:21.827Z
2017-10-27T15:13:21.827Z
ncmathsadist
<blockquote>
  <p>It was suggested I cross post this question from the main Stack
  Overflow site as it may be of interest here too</p>
</blockquote>

<p>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:</p>

<pre><code>int(5)
int(5.5)
int('5')
int('5.5')
</code></pre>

<p>The first three returned 5 as expected; the last one threw the error </p>

<blockquote>
  <p>ValueError: invalid literal for int() with base 10: '5.5'</p>
</blockquote>

<p>Given the behaviour of the first three lines how do I explain the error to a 14-year old (background = speaks 4 languages but is poor at maths)?</p>

<p>UPDATE </p>

<p>C# exhibits the same behaviour: <code>Convert.ToInt32("5.5")</code>; throws the error</p>

<blockquote>
  <p>Input string was not in a correct format.</p>
</blockquote>

CC BY-SA 3.0
2017-10-31T08:59:30.980Z
He doesn't need to be good at math to understand it, python isn't a programming language for first approach
Marco Salerno
CC BY-SA 3.0
2017-10-31T09:00:06.657Z
PS in c# you can do (int)5.5
Marco Salerno
<lesson-ideas><python>
How to explain the int() function to a beginner
# How to explain the int() function to a beginner

(Asked by: username_0 on 2017-10-26)

It was suggested I cross post this question from the main Stack
  Overflow site as it may be of interest here too

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 is poor at maths)?
UPDATE 
C# exhibits the same behaviour: Convert.ToInt32("5.5"); throws the error

Input string was not in a correct format.

**Tags:** lesson-ideas, python

> **Comments:**
> **username_1**: He doesn't need to be good at math to understand it, python isn't a programming language for first approach  
> **username_1**: PS in c# you can do (int)5.5  

---

## 3 answers

### Answer by username_2 on 2017-10-26. Score: 3

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 @username_3. 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.

> **Comments:**
> **username_3**: `int(eval(aString))` is very dangerous if `aString` comes from user input. It will allow the user to execute arbitrary code.  
> **username_2**: Excellent point. eval is a very big hammer.  
> **username_4**: I think this might also be well coupled with a lesson on "writing good specifications is hard."  You don't really get a sense for just how hard it is until many years into programming, but you can at least explain that spec writers have to make tradeoffs.  This might be well coupled with username_3's example of `int("36/5")`, which starts to show how hard it can be to draw the line on functionality.  

---

### Answer by username_3 on 2017-10-26. Score: 2

I agree with @username_2, but also.

* `int(42)` `"42" → 42` is one step: it converts string to int or throws.
* `int(7.2)` `7.2 → 7` is one step: it converts float/real to int (and rounds).
* `int("7.2")` `"7.2" → 7.2 → 7`✗ is two steps: convert string to float, and float to int.
* `int("36/5")` What about this? Should it be able to do this.

The problem that is causing the confusion is that we have effectively two functions. `int` taking a string, and `int` taking a float. They both do different things.

> **Comments:**
> **username_3**: @EllenSpertus, thanks I have now fixed the answer. It is now 42.  
> **username_5**: As I said below, type determines context.  This is an example of function overloading, which is covert in duck-typed Python and overt in statically typed C++ and Java.  

---

### Answer by username_5 on 2017-10-27. Score: 2

It is important to discuss the type system early, as it is the whole basis upon which objects interact. The type system is the species structure of the Python object ecosystem.

Strings interact with string behaviors: + is concatenation, [] is substringing, and \*(string,int) causes repetition.

Numbers, in the presence of arithmetic operators, do arithmetic.

The moral: type determines context and therefore regulates the interactions between objects.

The `int()` cast expects an object that is convertible into an integer. If it is passed a floating point number, it truncates the number towards zero. If it is passed a numerical string containing a valid parseable number, it extracts the number value from the string. If it is passed a boolean, it converts `true` to 1 and `false` to 0.

If it is passed something that is not a parseable into a number, it throws a `ValueError`.


---

