[Tutor] Floating point exercise 3 from Learn python the hard way

Walter Prins wprins at gmail.com
Mon Jun 13 23:10:54 CEST 2011


Hi,

On 13 June 2011 20:28, amt <0101amt at gmail.com> wrote:

>
>> Can you explain your reasoning? Why do you think line 3 needs
>> to be changed? Why line 5?
>
>
> Well the exercise says: "Rewrite ex3.py to use floating point numbers so
> it’s more accurate (hint: 20.0 is floating point)."
>
> I am honestly confused. I have read the exercise and found three lines that
> could use the floating point(2,3 and line 5). This is were the confusion is
> appearing. I can understand why at line 5 I use floating point. 6,75 is more
> precise than saying 7. But I can't understand at line 2 and 3. I mean it
> makes no difference for me. Saying 30 or 30.0 is the same thing. As well as
> saying 97 or 97.0.
>

OK, the point is that, although to *you* 30 and 30.0 is the same thing, the
fact is that to Python they're not the same thing.  Cast yourself back to
your 1st and 2nd grade math classes, where you learned about integer (whole
numbers) and integer maths (e.g integer division), then later on fractions
and rational numbers, and later still, irrational numbers and so on.  The
point is that Python similary interprets a number literal as a certain type,
and has a set of rules to decide how to handle arithmetic based on the types
of numbers it sees.  An expression such as:

1 / 2

consists of 2 integers and a division operator.  Now as humans we can
instantly interpret this in several ways.  Python will have one way that it
uses, unless you explicitly force it modify its interpretation.  Introducing
a float() call converts the paramter so that the output is a float, thus
affecting the rest of the expression.  Similarly, putting a "dot zero" after
a number forces Python to interpret it as a floating point number, thus
again affecting the rest of the expression evaluation.

Hope that helps.

Walter
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110613/d6499609/attachment.html>


More information about the Tutor mailing list