为什么赢得循环,循环?

时间:2013-10-13 00:56:25

标签: python loops break

我正在编写代码来生成前1000个素数,我不明白为什么这段代码不会按原样循环。

divisor = 1
guess = 2
count = 0
while count < 1000:
    divisor+=1
    while guess%divisor==0:
        if guess==divisor:
            print(guess)
            guess+=1
            count+=1
            divisor=1
        else:
            guess+=1
            divisor=1

如果我在if和else定义的末尾添加break(如下所示),那么循环运行正常如下,但我无法理解。

        if guess==divisor:
            print(guess)
            guess+=1
            count+=1
            divisor=1
            break
        else:
            guess+=1
            divisor=1
            break

3 个答案:

答案 0 :(得分:0)

你的循环运行良好,第一次guess==divisor为真,所以它会在fisrt时间进入else块后打印

变化:

else:
    guess+=1
    divisor=1

else:
    print("else ",guess)
    guess+=1
    divisor=1

你会发现它运行正常

答案 1 :(得分:0)

显然。条件:

guess%divisor==0

永远是真的......你做的是:

divisor=1
if和else语句

上的

然而,“break”是跳出while循环。所以在第二种情况下,你的代码工作正常。

答案 2 :(得分:0)

已更正:

divisor = 1
guess = 2
count = 0
while count<1000:
    divisor += 1
    if guess%divisor==0:            #'while' was replaced by 'if'
        if guess==divisor:
            print guess
            guess += 1
            count += 1
        else: guess += 1
        divisor = 1                 #moved here

输出:

2
3
5
7
11
13
17
...
7841
7853
7867
7873
7877
7879
7883
7901
7907
7919