Python Programming - Continue Statement

You can learn about Control Statements in Python Programs with Outputs helped you to understand the language better.

Python Programming – Continue Statement

The continue statement forces the next iteration of the loop to take place, skipping any statement(s) that follows the continue statement in the current iteration, i.e., the continue statement jumps back to the top of the loop for the next iteration.

Example 46.
Demo of continue statement.

# Demo of continue statement
count=0
while True:
count= count +1
# End loop if count is greater than 10
if (count > 10):
break
# Skip 5
if (count == 5):
continue
print(count)RUN
>>>
1
2
3
4
5
6
7
8
9
10
>>>

Figure 5.53 shows the use of the continue statement. At the top of the loop, the while condition is tested, and the loop is entered, if it’s true. Here, when the count is equal to 5, the program does not get to the print count) statement. So, the number 5 is skipped with the continue statement, and the loop ends with the break statement.’ Note in Figure 5.54, U is skipped due to the use of the continue statement.

Example 47.
Demo of continue statement.

# Demo of using continue statement
for ch in ‘COMPUTER’:
if (ch == ‘U’):
continue
print(ch)RUN
>>>
C
0
M
P
T
E
R
>>>

Example 48.
Program to print square of positive numbers.

# Program to print square of positive numbers
while True:
n = int(input(“Please enter an Integer: “))
if n< 0:
continue #this will take the execution back to the starting of the loop
elif n == 0:
break
print(“Square is “, n ** 2)
print(“Goodbye”)
RUN
>>>
Please enter an Integer: -4
Please enter an Integer: 2
Square is 4
Please enter an Integer: 3
Square is 9
Please enter an Integer: 0
Goodbye
>>>

Difference between break and continue statements

The continue statement skips the remainder of the statements in the body of a current iteration and starts execution immediately from the beginning of the next iteration. The break statement in the body of a loop terminates the loop. It exits from the current loop and starts execution from the statement following the loop.

  • break and continue can be used in both for and while statements.

Leave a Reply

Your email address will not be published. Required fields are marked *