我是Python的新手,我对“break”在for循环中的工作方式感到困惑。 Python文档中有一个例子(break and continue Statements),它计算范围内的素数(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')
,输出为:
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
然而,当我在代码中突然“突破”时:
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')
输出将是:
2 is a prime number
4 equals 2 * 2
6 equals 2 * 3
8 equals 2 * 4
你可以解释一下我突破“破解”后代码中会发生什么吗?谢谢
答案 0 :(得分:5)
当然 - 简单地说出“打破"打破"意味着它不再受" if"在它之前。
代码读取if语句,对其执行操作,然后无论if语句是true还是false,它都会执行" break"并退出for循环。
在第一个示例中,代码仅从'中删除。如果n%x == 0语句为真,则循环。
答案 1 :(得分:1)
尝试执行此代码 - 它可能会更清晰:
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')
我确定输出会帮助您了解正在发生的事情。只有满足if条件时#1才会中断,而#2中断,无论if条件是否满足,#2都会中断。