Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...