LearnWave
Learn it. Master it.

Flow of Control

break and continue

Choose between break and continue.

Two statements change the normal flow of a loop.

break ends the loop at once. Execution continues with the first statement after the loop. For example, a loop searches the list [4, 9, -2, 7] for the first negative number. Inside the loop, an if checks whether n < 0; if so, the program prints the number and runs break. Once -2 is found, there is no need to look further, so break ends the loop and 7 is never checked.

break is often used with while True, a loop whose condition is always true. It keeps going until a break stops it. For example, the book's Program 6-13 keeps adding the numbers the user types until a negative number is entered, then prints the total. The book's prime checker (Program 6-14) also uses break: once one factor is found, the number is not prime, and there is no point testing more.

continue skips the rest of the current iteration only, and jumps back to the start of the loop for the next one. It does not end the loop. For example, take a loop for i in range(1, 6) whose body says: if i == 4, continue; then print(i). It prints 1, 2, 3 and 5: only 4 is skipped.

Both break and continue work in for loops and in while loops.

break leaves the loop; continue skips one turn.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.