math.sqrt() in new 3.0 version : solution in input()
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri Dec 26 22:04:43 EST 2008
On Fri, 26 Dec 2008 20:34:45 -0600, David Lemper wrote:
> On Fri, 26 Dec 2008 15:52:24 -0600, David Lemper wrote:
>
>>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
>
> Problem is the new input() function. Yields a string.
>
> Thanks to Scott, Chris, Gabriel & John.
>
> Some thought I was not using the Python 3 command line. I was : Python
> 3.0 (r30:67507...
> Erratic behavior was that I was sometimes using n = input() and
> sometimes entering the integer directly into the math.sqrt() function,
> eg s = math.sqrt(4194304)
Ah, that explains it!
When you said that s = math.sqrt(n) worked at the command line, that is
what is technically known as a "falsehood" or "lie". Beginners often make
the mistake of telling falsehoods when they ask for help. The best way to
prevent this error is to read over what you wrote before hitting send,
take note of any place where you explicitly or implicitly suggest that
you did something, then ask yourself "Did I actually do that, or did I do
something different?"
If the answer is "I did something different", then you are about to tell
a falsehood, and the quality of the answers you get will correspondingly
suffer.
> I cannot find a mention of this in "The Python Tutorial release 3.1"
> The I&O section discusses output formatting and reading & writing text
> files.
I don't have Python 3 installed here. At the Python command line, what
does help(input) say?
--
Steven
More information about the Python-list
mailing list