Corsi registrati su
Corsi in diretta per la formazione di Front End Developer e Back End Developer
Python continue statement allows us to stop the current iteration to start over from the first statement of the loop (for or while) in which it was entered.
Python continue – first example
So let’s take a simple example to better understand how it works.
We enter numbers, if the number is negative we use the continue statement to make it skip all the other lines of code and start again from the beginning.
Here is the simple program:
i = 0 while i <3: n = int(input('Insert a number: ')) if n < 0: continue i += 1
In this case, therefore, if we insert a negative number, the counter is not incremented and the cycle continues to insert numbers until all 3 are positive.
Try the code in the online compiler that you will find at the following link: Python compiler online.
Python continue - second example
Let's take a second example of using the continue statement in Python.
We print numbers from 1 to 10, skipping the number 5.
Here, then, is an example with the for loop:
for i in range(1,11): if i == 5: continue print(i)
The output produced is this:
As we can see, the number 5 was not printed.
Python continue - third example
Let's take another example to better understand how this instruction works.
Print the numbers 1 to 10 by skipping multiples of 3.
Here is the sample code:
for i in range(1,11): if i % 3 == 0: continue print(i)
The output produced is as follows:
As we can see, the numbers 3, 6 and 9 were not printed.
In this short lesson we have explained how the continue statement works in Python through simple examples.
Some useful links
How to find the maximum of N numbers