程序如何使用break语句进行控制 [英] How the program has control with the break statement
问题描述
有人可以解释这个程序和它的输出吗?我对if陈述感到怀疑.我无法理解break语句在其中的工作原理:
Could anybody explain this program and output of this? I am having doubt at if statement. I'm not able to understand how break statement works in this:
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
推荐答案
break
语句无需输入else
子句即可退出循环.如果循环在未到达break
的情况下终止,则将输入else
子句.换句话说,循环搜索可能的除数;如果找到一个,则将其打印出来,并使用break
退出循环.如果未找到除数,则for循环正常"终止,然后输入else
子句(然后在子句中打印发现素数的子句).
The break
statement leaves the loop without entering the else
clause. If the loop terminates without reaching the break
, the else
clause will be entered. In other words, the loop searches for a possible divisor; if it finds one it prints it and leaves the loop using break
. If no divisor is found, the for loop terminates "normally" and thus enters the else
clause (in which it then prints that it has found a prime).
这篇关于程序如何使用break语句进行控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!