strange behavior of math.sqrt() in new 3.0 version

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Fri Dec 26 17:27:52 EST 2008


En Fri, 26 Dec 2008 19:52:24 -0200, <David at bag.python.org> escribió:

> I'm a newbee trying 3.0   Please help with  math.sqrt()
>
> At the command line this function works correctly
>       >>> import math
>               n = input("enter a number > ")
>               s = math.sqrt(n)
>      An entry of 9 or 9.0  will yield 3.0
>
> Yet the same code in a script gives an error message
>      Script1
>                    import math
>                    n = input("enter a number > ")
>                    s = math.sqrt(n)
>               Traceback (most recent call last) :
>                   File "<stdin>", line 1, in <module>
>                   File "script1.py" line 3 in <module>
>                      s = math.sqrt(n)
>                TypeError : a float is required
>      Entering 9 or 9.0 gives same error message.
>
>    According to the math module the results of all
>    functions are floats.  However it says nothing about
>    inputs.
>
> Strangely the above code runs fine in version 2.5  ( ? )
> and will handle large integers.
>
> I've read the documentation for 3.0 including the section
> "Floating Point Arithmetic: Issues & Limitations" and it
> helps nada.

And you won't find nothing - the change is in "input" behavior, not in the  
math functions.
For versions prior to 3.0, there are:

raw_input(message) -> string typed
input(message) -> result of evaluating the string typed

raw_input just returns whatever you type, as a string. Using the input  
function, Python evaluates whatever you type to obtain a result: if you  
type the three characters "nine" "dot" "zero" the result is the double  
9.0; you can even type (17+1)/2.0 to get the same value (try it with your  
Python 2.5)

Since version 3.0, input behaves as raw_input in the older versions, and  
there is no builtin function equivalent to the old input function.
Use this instead:

n = float(input("enter a number > "))


-- 
Gabriel Genellina




More information about the Python-list mailing list