简体   繁体   English

break 如何在 for 循环中工作?

[英]How does break work in a for loop?

I am new in Python and I got confused about the way that "break" works in a for loop.我是 Python 的新手,我对“break”在 for 循环中的工作方式感到困惑。 There is an example in Python documentation( break and continue Statements ) which calculates prime numbers in range (2, 10): Python 文档( break 和 continue 语句)中有一个示例计算范围 (2, 10) 内的素数:

for n in range(2, 10):
   for x in range(2, n):
       if n % x == 0:
           print(n, 'equals', x, '*', n//x)
           break
   else:
       # loop fell through without finding a factor
       print(n, 'is a prime number')

and the output is:输出是:

2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

however when I outdent "break" in the code:但是,当我在代码中取消缩进“break”时:

for n in range(2, 10):
   for x in range(2, n):
       if n % x == 0:
           print(n, 'equals', x, '*', n//x)
       break
   else:
       # loop fell through without finding a factor
       print(n, 'is a prime number')

the output will be:输出将是:

2 is a prime number
4 equals 2 * 2
6 equals 2 * 3
8 equals 2 * 4

Can you please explain what happens in the code after I outdent "break"?你能解释一下在我取消缩进“break”之后代码中发生了什么吗? Thank you谢谢

Sure - Simply put out-denting the "Break" means it's no longer subject to the "if" that precedes it.当然 - 简单地把“Break”去掉就意味着它不再受制于它之前的“if”。

The code reads the if statement, acts on it, and then regardless of whether that if statement is true or false, it executes the "break" and drops out of the for loop.代码读取 if 语句,对其进行操作,然后无论该 if 语句是真还是假,它都会执行“break”并退出 for 循环。

In the first example the code only drops out of the 'for' loop if the n%x==0 statement is true.在第一个示例中,如果 n%x==0 语句为真,代码只会退出“for”循环。

Try executing this code - it might make it more clear:尝试执行这段代码 - 它可能会更清楚:

for n in range(2, 10):
for x in range(2, n):
    if n % x == 0:
        print(n, 'equals', x, '*', n//x)
        break
    print('loop still running...')
else:
    # loop fell through without finding a factor
    print(n, 'is a prime number')

vs:对比:

for n in range(2, 10):
for x in range(2, n):
    if n % x == 0:
        print(n, 'equals', x, '*', n//x)
    break
    print('loop still running...')
else:
    # loop fell through without finding a factor
    print(n, 'is a prime number')

I'm sure the output would help you understand what is going on.我相信输出会帮助您了解正在发生的事情。 #1 is breaking only if the if condition is satisfied, while #2 breaks always regardless of the if condition being satisfied or not. #1 仅在满足 if 条件时才会中断,而无论是否满足 if 条件,#2 都会中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM