程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Detailed explanation of the usage and differences of break, continue, pass and else in Python

編輯:Python

python There are two circular reserved words in :break and continue.

  • effect : Loop execution of auxiliary control program .
  • break Statement and continue The difference between sentences :break Statement is the process of ending the whole loop , It is not necessary to judge whether the condition for executing the loop is true ;continue Statement is to end only this loop , Does not terminate the execution of the entire loop .

1. break

  • effect : Used to jump out of the innermost layer for Loop or while loop , After leaving the loop, the program continues to execute after the loop code . namely break Statement can only jump out of the loop of the current level .

  • Example :

for i in "python":
for j in range(5):
print(i, end="")
if i == "t":
break
# The result of program execution is :pppppyyyyytooooonnnnn

This example shows ,break The statement jumps out of the innermost for loop , But you can also perform an outer loop .

2. continue

  • effect : End the current cycle , That is, jump out of the statement that has not been executed in the loop body , But it doesn't jump out of the current loop .
  • Example :
for i in "python":
if i == "t":
continue
print(i, end="")
# The result of program execution is :pyhon
for i in "python":
if i == "t":
break
print(i, end="")
# The result of program execution is :py

3. pass

  • effect : Do nothing , It only plays a role of occupying . Use in loop pass Don't jump out of the loop
  • Example :
for i in "python":
if i == "t":
pass
print(i, end="")
# The result of program execution is :python

4. for Circulation and while In the loop else Extended usage

  • explain :else The program in is executed under only one condition , That is, the loop normally traverses all contents or ends the loop because the condition does not hold , There is no reason break perhaps return And out of the loop .continue Yes else No impact
  • Example :
for i in "python":
if i == "t":
continue
print(i, end="")
else:
print(" Program exit normally ")
# The result of program execution is : pyhon Program exit normally 
for i in "python":
if i == "t":
break
print(i, end="")
else:
print(" Program exit normally ")
# The result of program execution is : py

matters needing attention : Remember break Statement and continue The difference between sentences

Articles you may be interested in :

  1. Python And global sentence , How to distinguish local variables from global variables

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved