How to use continue statement in nested loops In Python
A continue statement is also a type of loop control statement. It is just the opposite of the break statement. The continue statement forces the loop to jump to the next iteration of the loop whereas the break statement terminates the loop. Let’s understand it by using code.
Python3
# Running outer loop from 2 to 3 for i in range ( 2 , 4 ): # Printing inside the outer loop # Running inner loop from 1 to 10 for j in range ( 1 , 11 ): if i = = j: continue # Printing inside the inner loop print (i, "*" , j, "=" , i * j) # Printing inside the outer loop print () |
Output:
2 * 1 = 2 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10 2 * 6 = 12 2 * 7 = 14 2 * 8 = 16 2 * 9 = 18 2 * 10 = 20 3 * 1 = 3 3 * 2 = 6 3 * 4 = 12 3 * 5 = 15 3 * 6 = 18 3 * 7 = 21 3 * 8 = 24 3 * 9 = 27 3 * 10 = 30
Time Complexity: O(n2)
Auxiliary Space: O(1)
In the above code instead of using a break statement, we are using a continue statement. Here when ‘i’ becomes equal to ‘j’ in the inner loop it skips the rest of the code in the inner loop and jumps on the next iteration as we see in the output “2 * 2 = 4” and “3 * 3 = 9” is not printed because at that point ‘i’ becomes equal to ‘j’.
Python Nested Loops
In Python programming language there are two types of loops which are for loop and while loop. Using these loops we can create nested loops in Python. Nested loops mean loops inside a loop. For example, while loop inside the for loop, for loop inside the for loop, etc.