Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 我的素性测试忽略了一个条件。我做错了什么?_Python_Loops - Fatal编程技术网

Python 我的素性测试忽略了一个条件。我做错了什么?

Python 我的素性测试忽略了一个条件。我做错了什么?,python,loops,Python,Loops,作为一个python新手爱好者,我觉得这很烦人: def isPrime(x): if x < 0: raise Exception("The number is negative.") if x == 0 or x == 1: return False if x == 2: return True else: if x % 2 == 0: return False for i in xrange (3, int(math.s

作为一个python新手爱好者,我觉得这很烦人:

def isPrime(x):
    if x < 0: raise Exception("The number is negative.")
    if x == 0 or x == 1: return False
    if x == 2: return True
    else:
        if x % 2 == 0: return False
        for i in xrange (3, int(math.sqrt(x)), 2): #-------> This doesn't do anything.
            if x % i == 0: return False # Even if I put 3 instead of i, it still prints numbers that are divisible by 3.
    return True

for i in xrange (100):
    if isPrime(i):
        print i
def isPrime(x):
如果x<0:引发异常(“数字为负数”)
如果x==0或x==1:返回False
如果x==2:返回True
其他:
如果x%2==0:返回False
对于xrange中的i(3,int(math.sqrt(x)),2):#----->这没有任何作用。
如果x%i==0:返回False#即使我输入3而不是i,它仍然打印可被3整除的数字。
返回真值
对于X范围内的i(100):
如果是(i):
打印i
我得到像9,15,21这样的数字-可以被3整除,因此不是素数。我遗漏了什么?

您想要
xrange(3,int(math.sqrt(x))+1,2)
-请记住
xrange
迭代所有值,从其起点(包含)到终点(独占)


更具体地说,当
x
为9时,就有了
xrange(3,3,2)
,它不会迭代任何东西。

捕捉得好!为了OP的利益,这被称为。这很常见,足以证明它自己的维基百科文章是正确的。