If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, the
continue
statement is used to skip the rest of the current iteration of a loop and proceed to the next iteration. When thecontinue
statement is encountered inside a loop (e.g.,for
orwhile
loop), the remaining code in that iteration is skipped, and the loop moves to the next iteration to continue its execution.The
continue
statement is often used in combination with conditional statements (if
,else
,elif
) to control when to skip the current iteration.Here's an example of how the
continue
statement works in afor
loop:pythonCopy code
for num in range(1, 6): if num == 3: continue print(num)
Output:
Copy code
1 2 4 5
In this example, the
for
loop iterates over the numbers from 1 to 5 using therange()
function. When the value ofnum
becomes 3, theif
statement checks the conditionnum == 3
, which evaluates toTrue
. As a result, thecontinue
statement is executed, causing the rest of the code inside the loop to be skipped for the current iteration. Therefore, the number 3 is not printed, and the loop proceeds to the next iteration, printing the other numbers.The
continue
statement can also be used with awhile
loop to skip the current iteration based on specific conditions.Example using
continue
with awhile
loop:pythonCopy code
count = 0 while count < 5: count += 1 if count == 3: continue print("Current count:", count)
Output:
sqlCopy code
Current count: 1 Current count: 2 Current count: 4 Current count: 5
In this example, the
while
loop iterates whilecount
is less than 5. When the value ofcount
becomes 3, theif
statement withcontinue
is executed, causing the rest of the code inside the loop for that iteration to be skipped. Therefore, the number 3 is not printed, and the loop proceeds to the next iteration.The
continue
statement is useful when you want to skip specific iterations of a loop based on certain conditions. It allows you to control the flow of your program more precisely and avoid executing unnecessary code.
Comments: 0