If cucumbers isn’t a float, how did total_cost end up being a float?
Answer
When we do math between an integer and a float, the result will always be a float. This is a good rule to keep in mind because it can cause unexpected and incorrect values if you try dividing two integer values that are not evenly divisible. The simple solution is what we’ve done in this exercise: convert one of the involved numbers to a float so that the result becomes a float.
At Numbers, section 9/14 in the first part of learning Python, I was fine with instructions 1-3 but got stopped on #4, "Print out total_cost. What datatype is it?"
Usually there is a hint available to concisely explain what to do, but not in this case.
What is wrong with my code? and where did I miss the instruction?
Please include a link to the exercise that this relates to. The example given has no context.
Python 2 division quotient is dependent on data types of the operands. If both are integer, the quotient is integer. When one or the other, or both are floats, the quotient is a float.
7 / 3 => 2
7 / 3. => 2.3333333333333335
From a standpoint of explicitness in readability,
float(7) / 3 => 2.3333333333333335
Python 3 has removed this conditional treatment of quotients by making all quotients a float, by default.
5 / 2 => 2.5
If an integer is the intended result, then explicit casting is required…
That line is unexpected, probably, and should be removed.
Whenever you see code written like this,
>>> type(total_cost)
<type 'float'>
>>>
it means the command was entered directly at the interactive console, and the interpreter responds immediately. In a code statement we need to assign expressions such as this, or print them.