Heim  >  Artikel  >  Backend-Entwicklung  >  Python跳出循环语句continue与break的区别

Python跳出循环语句continue与break的区别

WBOY
WBOYOriginal
2016-06-16 08:42:331473Durchsuche

虽然在Python中的for循环与其它语言不大一样,但跳出循环还是与大多数语言一样,可以使用关键字continue跳出本次循环或者break跳出整个for循环。
break

复制代码 代码如下:

# encoding=UTF-8
 
for x in range(10):
    if x==5:
        break
 
    print x

上面使用的break循环,所以执行到x==5的时候就跳出了整个for循环,因此print x语句只打到4的时候就终止了,因此输出结果如图:

continue

复制代码 代码如下:

# encoding=UTF-8
 
for x in range(10):
    if x==5:
        continue
 
    print x

上面循环使用了continue跳出本次循环,因此只有在x==5的时候跳出本次循环,接着下次继续,因此print x语句只有在x==5的时候没有执行到,其它值均执行到了,输出结果如图:

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn