Python break and continue With Examples

Today we will learn about Python break and continue statements. In previous post, we learnt about python while loop.

Python Break and Continue

Python break and continue statements are used only in loop. It helps to modify loop behaviour. Suppose you’re executing a loop, at one phase you need to terminate the loop or skip some statements then you need these statements.

Python break

This statement is used to break the loop. Suppose you’re printing odd numbers using while loop. But you don’t need to print numbers greater than 10. Then you can write the following python code.

Python break example output

Python Break and Continue

In the given example you will see that the statement(s) that are written after break, won’t be executed. So here, 11 will not be printed.

Python break statement can be used in for loop also. Suppose you are printing words from a list. If any words that matches with “exit” won’t be printed and the loop will terminate. The following python code illustrates the idea.

Python break for example

until_exit

Python continue

Python continue statement is used to skip the statement of the loop and iterate to the next step. For example you’re printing number 1 to 10. You need to skip all statements at step 7. The following python code illustrates the scenario.

Python continue example output

Python Break and Continue

Same thing you can do for while loop. Suppose, you are trying to print all the odd values from 1 to 10, then the python code which solves the problem would be:

Python continue example while loop

Python Break and Continue

That’s all about python break and continue statement. Hope that you have learnt well. If you have any query about this topic, feel free to ask that in comment section.
#HappyCoding

By admin

Leave a Reply

%d bloggers like this: