Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
743 views
in Technique[技术] by (71.8m points)

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 = False
    if isprime == False:
        print("Not Prime")
    else:
        print("It's Prime!")

And everything works besides the square root part. getting error: TypeError: a float is required. I changed while i <= to while float(i) <=, but that did not fix the error! What do I do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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                                                                                                
Python 2.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 19 2011, 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 18 2011, 16:24:40) [GCC] on linux2                                                        
Type "help", "copyright", "credits" or "license" for more information.
>>> type(input())
5
<class 'str'>
>>> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...