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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/opencv/3.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
Loops python中是否可以嵌套for循环?_Loops_Iteration - Fatal编程技术网

Loops python中是否可以嵌套for循环?

Loops python中是否可以嵌套for循环?,loops,iteration,Loops,Iteration,我正在开发一个程序,该程序可以查找素数,以便了解for循环。我有一些素数的列表,可以用来检查%==0。我试过这个 primes = [1, 3, 5, 7, 9, 11, 13, 17, 19, 29] hold_the_primes = [] for x in range(29,841): for y in primes: if x % y == 0: pass else: hold_the_primes.

我正在开发一个程序,该程序可以查找素数,以便了解for循环。我有一些素数的列表,可以用来检查%==0。我试过这个

primes = [1, 3, 5, 7, 9, 11, 13, 17, 19, 29]
hold_the_primes = []
for x in range(29,841):
    for y in primes:
        if x % y == 0:
            pass
        else:
            hold_the_primes.append(x)
primes.extend(hold_the_primes)
for x in primes:
    print x

但是它什么也不返回,终端在这一点上卡住了。我能做些什么来实现这一点呢?

嵌套循环在python中是可能的。我相信问题在于你的代码

以下是一些要点:

1不是素数,列表应该以2开头。你还缺了23个。 看起来你是在假设一个数不能被素数整除,它就是素数。我认为这不是合适的支票。例如,如果x=29,hold_,则当y=3、5、7、9、11、13、17和19时,将调用appendx。 如果一个数除了1和它本身没有其他因子,那么它就是素数 编辑如果您所做的只是将第二个for循环移动到一个函数中,我想您会看到您的代码没有按照预期的方式运行 以下是一个我认为有效的例子:

primes = [2, 3, 5, 7, 9, 11, 13, 17, 19, 23, 29]
hold_the_primes = []

def isPrime(n):
    temp = 2;
    while temp*temp <= n: #temp < math.sqrt(n):
        if n % temp == 0:
            return False
        temp += 1
    return True

for x in range(30,841):
    if isPrime(x):
        hold_the_primes.append(x)


primes.extend(hold_the_primes);
for x in primes:
    print x

我已经弄明白了。我刚刚定义了一个名为primetest的函数,它包含第二个for循环。终端卡住是什么意思?但要回答您的问题,可以使用yes嵌套for循环。代码中的逻辑是关闭的,但从语法上讲,它是可以工作的,并且可以在我的终端中打印一些东西。