HOME HTML EDITOR C JAVA PHP python

Python Loops

Loops in Python let you execute a block of code repeatedly as long as a condition holds or while iterating through a sequence (such as a list, tuple, string, or range). Python provides two main loop types: for loops and while loops.

1. The for Loop

A for loop iterates over each item in a sequence or iterable object:

languages = ["Python", "Java", "C++"]

for lang in languages:
    print(lang)

2. Using range() in a for Loop

The built-in range() function generates a sequence of numbers — ideal when you want a loop to run a specific number of times:

# Prints 0, 1, 2, 3, 4
for i in range(5):
    print(i)

# Prints even numbers from 2 to 10 (start, stop, step)
for num in range(2, 11, 2):
    print(num)

3. The while Loop

A while loop runs repeatedly as long as its condition evaluates to True. Always update the loop variable so it eventually becomes False and avoids an infinite loop:

count = 1

while count <= 5:
    print("Count:", count)
    count += 1

4. break and continue Statements

Use break to exit a loop early, and continue to skip the current iteration and move to the next one:

for i in range(1, 8):
    if i == 3:
        continue    # Skip 3
    if i == 6:
        break       # Stop loop at 6
    print(i)

5. The else Clause with Loops

An optional else block attached to a for or while loop runs when the loop finishes normally (without hitting a break statement):

for n in range(1, 4):
    print("Checking:", n)
else:
    print("Loop completed without break.")
Tip: Use a for loop when you know the items or number of iterations in advance, and a while loop when repetition depends on a dynamic condition.