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 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…