[Tutor] eval and floating point

wesley chun wescpy at gmail.com
Thu Jan 15 19:28:27 CET 2009


>>> eval("float(3/2)")
>>
>> That still does not work, because the 'float' comes after the
>> division. 3/2 equals 1, so float(3/2) equals 1.0. To make it work,
>> you'll have to put the float inside the division:
>> eval("float(3)/2")

correct. as long as one of the operands is a float, the division will
be (or rather, the division *won't* be integer), i.e., "3./2" or
"3/2.".

> the "import future" trick is probably the only solution that will work,
> short of parsing the string and doing the division without using eval...

in addition to the import of division from __future__, which adds one
extra line of code to all your source files which need this
functionality, you can also use -Qnew to launch the interpreter, which
defaults to the 3.x true division semantics:

$ python -Qnew
Python 2.4.5 (#1, May  9 2008, 12:23:22)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 3/2
1.5

hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com


More information about the Tutor mailing list