PythonSyntax and keywords
break and continue
Breaking out of a loop, or skipping to its next pass.
Example
#Python
answers = ["A", "", "C", "STOP", "B"]
for answer in answers:
if answer == "":
continue
if answer == "STOP":
break
print("Answer:", answer)Resultsaved result, you can check it
Answer: A
Answer: C
Definition and usage
#The break statement immediately ends the nearest for or while loop. The program moves on to the code after the loop. It is useful once you have found what you were looking for and further checking makes no sense.
The continue statement skips the rest of the current pass and moves straight to the next one. It is used to skip items that do not meet a condition.
Both statements affect only the nearest loop. In nested loops, break in the inner loop does not stop the outer one. In that situation, it is often clearer to pull the code out into a function and use return.
Syntax
#Syntax
for element in collection:
if condition:
continue
if other:
breakGood practices
#- Instead of
continueat the start of a loop, you can filter the data with a list comprehension. - To break out of several nested loops at once, pull them into a function and use
return.
Related entries
#Spotted a mistake or missing an example? Write to us.