Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

python - 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. There is an example in Python documentation(break and continue Statements) which calculates prime numbers in range (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:

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"? Thank you

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Sure - Simply put out-denting the "Break" means it's no longer subject to the "if" that precedes it.

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.

In the first example the code only drops out of the 'for' loop if the n%x==0 statement is true.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...