Hello everyone! Welcome back to our Python series on CipherTrick.com. Today we’re going to learn about nested loops and loop control statements in Python. These tools give us more control and flexibility in our code, allowing us to handle more complex tasks.
Part 1: Nested Loops
A nested loop is a loop inside another loop. It allows you to “loop through a loop”, handling more complex iteration patterns. Here’s a basic example with a
for loop inside another
for i in range(3): for j in range(3): print(i, j)
This code will print each combination of
j for the numbers 0 to 2.
Nested loops can also involve
i = 0 while i < 3: j = 0 while j < 3: print(i, j) j += 1 i += 1
This code does the same thing as the previous example, but using
Part 2: Loop Control Statements
Loop control statements change the execution from its normal sequence. Python supports three types of loop control statements:
break statement is used to exit a loop prematurely, stopping the loop even if the loop condition has not become False or the sequence of items has not been completely iterated over. Here’s an example:
for i in range(5): if i == 3: break print(i)
This will print the numbers 0, 1, and 2. When
i is equal to 3, the
break statement stops the loop.
continue statement is used to skip the rest of the code inside a loop for the current iteration only. The loop does not terminate but continues on with the next iteration. Here’s an example:
for i in range(5): if i == 3: continue print(i)
This will print the numbers 0, 1, 2, and 4. When
i is equal to 3, the
continue statement skips the print operation for that iteration.
pass statement is a placeholder and is used when the syntax requires a statement, but you don’t want any command or code to execute. The
pass statement is mostly used for creating minimal classes or defining empty loops. Here’s an example:
for i in range(5): pass
This code is perfectly valid but doesn’t actually do anything.
Nested loops and loop control statements are key features of Python, allowing for complex iteration patterns and greater control over how and when your loops execute. Practice using these concepts in your code until you feel comfortable with them. Up next in our Python tutorial series, we’ll explore Python’s data structures in more detail. Until then, keep practicing and happy coding!