Skip to content

Python Loops

In programming, we often need to execute a block of code multiple times. Instead of writing the same code repeatedly, we use loops.

Loops are control structures that allow for repeated execution of a code block based on a condition or by iterating over a sequence.

Conceptual Flow of a Loop:

  1. Check a condition or get the next item from a sequence.
  2. If the condition is true or items remain: Execute the loop body.
  3. Go back to step 1.
  4. If the condition is false or no items remain: Exit the loop and continue with the code after the loop.

Python provides two primary types of loops:

Loop TypeDescription
while loopRepeats a block of code as long as a given condition remains True. The condition is tested before each execution of the loop body.
for loopIterates over the items of any sequence (like a list, tuple, string, or range) or other iterable object, executing a block of code once for each item.
nested loopsYou can place one loop inside another. This is useful for working with multi-dimensional data structures or complex iteration patterns.

Note: Python does not have a do..while loop construct found in some other languages, where the loop body is guaranteed to execute at least once before the condition is checked.

Loop control statements alter the normal execution flow within loops:

Python supports the following control statements:

Control StatementDescription
break statementImmediately terminates the current loop (the innermost loop if nested) and transfers execution to the statement following the loop.
continue statementSkips the rest of the code inside the current iteration of the loop and proceeds to the next iteration (re-evaluating the condition in a while loop or getting the next item in a for loop).
pass statementActs as a null operation. It’s used when a statement is syntactically required but you don’t want any command or code to execute. It’s often used as a placeholder during development.
count = 0
while count < 5:
print(f"Count is: {count}")
count += 1 # Important: Increment counter to avoid infinite loop
print("Loop finished!")
for i in range(3): # range(3) generates numbers 0, 1, 2
print(f"Iteration {i}")
print("Loop finished!")
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"Current fruit: {fruit}")
print("Loop finished!")
for i in range(10):
if i == 5:
print("Breaking loop")
break # Exit the loop when i is 5
print(f"i = {i}")
print("After the loop")
for i in range(5):
if i == 2:
print("Skipping iteration 2")
continue # Skip the rest of this iteration
print(f"Processing i = {i}")
print("After the loop")