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

Chris Rebert clp at rebertia.com
Fri Dec 26 23:16:30 CET 2008


On Fri, Dec 26, 2008 at 1:52 PM,  <David at bag.python.org> wrote:
> 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 > ")

raw_input() was renamed input() in Python 3.0, and it returns a
*string*, not a *number*.
Therefore, you need to convert the string to an int or float.

Change the line to:

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

And it should work just fine.

>              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

You're currently giving it a string, not a number, which is
nonsensical, hence the TypeError. I presume ints would be coerced to
floats by the function.

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

You should read "What's New in Python 3.0", it covers changes such as
the one you've encountered -
http://docs.python.org/3.0/whatsnew/3.0.html

Cheers,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com



More information about the Python-list mailing list