</>
CompilerOnline
Open Interactive Editor

Python Loops: For & While

Iteration in Python

Python has two primitive loop commands: for and while. Loops are essential constructs that allow you to execute a block of code multiple times, reducing repetition and automating repetitive tasks.

For Loops

A for loop is used for iterating over a sequence (such as a list, a tuple, a dictionary, a set, or a string). Unlike traditional loops in other languages that rely on counter increments, Python's for loop acts like an iterator method, traversing items in the order they appear in the collection.

The range() function is commonly used alongside for loops to generate a sequence of numbers. For example, range(5) yields numbers from 0 to 4. You can also specify start, stop, and step arguments, such as range(1, 10, 2) to get odd numbers up to 9.

While Loops

With the while loop, we can execute a set of statements as long as a condition is true. It is commonly used when the number of iterations is not known in advance, such as reading input until a user quits.

Python loops also support control statements: break terminates the loop prematurely, continue skips the rest of the current iteration and moves to the next, and the unique else block executes only when the loop terminates naturally without hitting a break.

Control Flow with Break

The break statement in Python is used to exit a loop completely when a secondary condition is met, bypassing the main loop condition. This is highly useful for searching algorithms where you exit as soon as the target item is located.

python
for n in range(1, 10):
    if n == 5:
        break
    print("Number:", n)
python
# For loop using range
print("For loop output:")
for i in range(1, 6):
    print(f"Count: {i}")

# While loop
print("\nWhile loop output:")
n = 3
while n > 0:
    print(f"Countdown: {n}")
    n -= 1