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

John Machin sjmachin at lexicon.net
Fri Dec 26 23:57:34 CET 2008


On Dec 27, 8:52 am, David Lemper wrote:
> I'm a newbee trying 3.0   Please help with  math.sqrt()

math.sqrt() is not the problem.

> 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

I can't reproduce this. See below. Are you sure that you weren't using
Python 2.x? Start with a fresh Python 3.0, and please copy/paste
*exactly* what is on the screen, like I've done:

C:\junk>\python30\python
Python 3.0 (r30:67507, Dec  3 2008, 20:14:27) [MSC v.1500 32 bit
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> n = input("float-> ")
float-> 9
>>> type(n)
<class 'str'>
>>> repr(n)
"'9'"
>>> import math
>>> s = math.sqrt(n)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a float is required

All of the above is exactly as expected. input() returns a string.
math.sqrt expects a float.

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

Again, as expected.

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

Suggestion: either choose ONE of 2.6 and 3.0 to learn Python, or plan
to spend a lot of time being confused, or reading "What's new in
Python 3.0" -- a relevant snippet of which is:
"""
PEP 3111: raw_input() was renamed to input(). That is, the new input()
function reads a line from sys.stdin and returns it with the trailing
newline stripped. It raises EOFError if the input is terminated
prematurely. To get the old behavior of input(), use eval(input()).
"""

HTH,
John



More information about the Python-list mailing list