[英]a code that understands a number is prime or normal at Python
I'm new in Python and write this code for recognizing a number is prime or not. 我是Python的新手,请编写此代码来识别数字是否为质数。 I wrote a code that works in JavaScript and visual Basic, but didn't work in Python and its error is: TypeError:a float is required .
我写了一个可以在JavaScript和Visual Basic中运行的代码,但是在Python中却没有运行,它的错误是: TypeError:需要浮点数 。 my code:
我的代码:
import math
a = raw_input("Enter a number:")
k = 0
i = 1
s = math.sqrt(a)
while i <= s:
if a % i == 0:
k += 1
i += 1
if k == 2:
print "prime num"
else:
print "normal num"
what's wrong? 怎么了?
Just convert the user input to int
. 只需将用户输入转换为
int
。 a = int(raw_input("Enter a number:"))
What's wrong is that you were trying to find the square root of a value of type string
(text). 出问题的是,您试图查找
string
(文本)类型的值的平方根。
There are more issues in your code: while
loop is only up to square root of a given number, but you print prime num
for k==2. 您的代码中还有更多问题:
while
循环仅达到给定数字的平方根,但是您打印k == 2的prime num
。 In this code there will be only one divisor, and it is 1. 在此代码中,只有一个除数,即为1。
What is more, you can start from i=2
, so there will be 0 divisors for a prime number. 而且,您可以从
i=2
开始,因此质数将有0个因数。 After that, last issue is that 1 is not a prime number. 之后,最后一个问题是1不是质数。 So the code looks like that:
因此,代码如下所示:
import math
a = int(raw_input("Enter a number:"))
k = 0
i = 2
s = math.sqrt(a)
#print(s)
while i <= s:
if a % i == 0:
k += 1
i += 1
#print(k)
if k == 0 and a > 1:
print "prime num"
else:
print "normal num"
首先检查您的python版本,如果您使用的是python3,则仅使用a=input("enter number")
raw_input适用于python2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.