Skip to content Skip to sidebar Skip to footer

Float Bug On Square Root Function Python

I have the code: #!/usr/bin/env python import math i = 2 isprime = True n = input('Enter a number: ') while i <= math.sqrt(n): i += 1 if n % i == 0: isprime = Fa

Solution 1:

input(...) returns a string. You are trying to take the sqrt("of a string"). Use int(input("Enter a number: ")) instead.

Even though you claim to be using python2 with #!/usr/bin/env python, make sure that python is actually python2. You can check this by just typing:

/usr/bin/env python

In a terminal and looking at the version number, e.g.:

% /usr/bin/env python                                                                                                
Python2.7.2 (default, ...
...

If it is set to Python 3.x, this is a problem with your system administrator. This should not be done and should immediately be changed. Python3 programs must be invoked with python3; this "tweak" will break any python2 programs on the current Linux system.


Apparently input is equivalent to eval(raw_input(...)) so would work in python2, but wouldn't in python3.:

% python2                                                                                                            
Python 2.7.2 (default, Aug 192011, 20:41:43) [GCC] on linux2                                                        
Type"help", "copyright", "credits"or"license"for more information.
>>> type(input())
5
<type'int'>
>>> 

Versus:

% python3                                                                                                            
Python 3.2.1 (default, Jul 182011, 16:24:40) [GCC] on linux2                                                        
Type"help", "copyright", "credits"or"license"for more information.
>>> type(input())
5
<class'str'>
>>> 

Solution 2:

I think you are using Python3. In python3 input returns string.

>>> x = input()
2>>> type(x)
<class'str'>
>>> math.sqrt(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: a floatis required

Type-cast string to float and it should work just fine.

>>>math.sqrt(float(x))
1.4142135623730951
>>>

Post a Comment for "Float Bug On Square Root Function Python"