程序如何使用break语句进行控制 [英] How the program has control with the break statement

查看:83
本文介绍了程序如何使用break语句进行控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释这个程序和它的输出吗?我对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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆