Python Loops

What are Loops?

Loops allow you to repeat a block of code multiple times. Python has two main types of loops: for loops and while loops.

For Loops

For loops are used to iterate over a sequence (like a list, range, or string). The most common pattern is using range():

# Print numbers from 1 to 5
for i in range(1, 6):
    print(f"Iteration {i}")

# Output:
# Iteration 1
# Iteration 2
# Iteration 3
# Iteration 4
# Iteration 5

Interactive Example

Try editing the code below and click "Run" to see different loop patterns in action:

Initializing Python environment...
Output
(No output yet)

While Loops

While loops continue executing as long as a condition is True. Be careful to avoid infinite loops!

# Count from 0 to 2
count = 0
while count < 3:
    print(f"Count: {count}")
    count += 1

# Output:
# Count: 0
# Count: 1
# Count: 2

Loop Control Statements

  • break: Exit the loop immediately
  • continue: Skip the current iteration and move to the next
  • pass: Do nothing (placeholder)
# Using break
for i in range(10):
    if i == 5:
        break  # Stop when i is 5
    print(i)  # Prints 0, 1, 2, 3, 4

# Using continue
for i in range(5):
    if i == 2:
        continue  # Skip when i is 2
    print(i)  # Prints 0, 1, 3, 4

Iterating Over Lists

For loops can iterate directly over list items:

fruits = ["apple", "banana", "cherry"]

for fruit in fruits:
    print(f"I like {fruit}")

# Output:
# I like apple
# I like banana
# I like cherry