Python break and continue Statement

In Python, break and continue statements apply in loops which can alter the flow of a loop. Loops iterate over a block of code until test expression becomes false, in case is some reason we want to alter the flow of a loop the break and continue statements are used in these cases.


break statement

The break statement terminates the loop once break statement is encountered and control moves to the statement immediately after the body of the loop. If it is inside a nested loop (loop inside another loop), break will terminate the innermost loop.

Example: Python break

# Program to show the use of break statement inside loop for char in "break": if char == "a": break print char, print("The end") #Output b r e








In this program, we iterate through the "string" sequence. We check if the letter is "i", upon which we break from the loop. Hence, we see in our output that all the letters up till "i" gets printed. After that, the loop terminates.

continue statement

The continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration.

Example: Python continue

# Program to show the use of continue # statement inside loops for char in "Break": if char == "a": continue print val, print("The end") #Output b r e k #The end






This program is same as the above example except the break statement has been replaced with continue. We continue with the loop, if the string is "i", not executing the rest of the block. Hence, we see in our output that all the letters except "i" gets printed.