Advertisement
❮ Previous: Python Match...Case Next: Python For Loops & Range ❯

Python While Loops

Python While Loops: Mastering break, continue, and else

A while loop in Python repeatedly executes a block of code as long as a given condition evaluates to True. Unlike for loops, which iterate over a sequence, while loops are condition-driven and run until that condition becomes False.


1. Basic while Loop Syntax

count = 1
while count <= 5:
    print(f"Count is: {count}")
    count += 1

Try this code ❯


Advertisement

2. Controlling Loops: break and continue

Python provides flow control statements to alter how loops execute:

The break Statement

The break statement immediately exits the loop entirely, bypassing any remaining code and the loop's condition check.

# Stop searching when the target number is found
number = 1
while number <= 10:
    if number == 7:
        print("Target found! Breaking out of loop.")
        break
    print(f"Checking number: {number}")
    number += 1

Try this code ❯

The continue Statement

The continue statement skips the rest of the code inside the current iteration and jumps straight back to the loop's condition evaluation for the next cycle.

# Skip printing even numbers
num = 0
while num < 5:
    num += 1
    if num % 2 == 0:
        continue  # Skips the print statement for even numbers
    print(f"Odd number: {num}")

Try this code ❯


Advertisement

3. The Unique else Clause in Python Loops

One of Python's unique features is the ability to attach an else block to a while (or for) loop.

attempts = 3
while attempts > 0:
    password = input("Enter password: ")
    if password == "secret123":
        print("Access granted!")
        break
    attempts -= 1
else:
    # This triggers ONLY if the loop finishes without hitting the 'break'
    print("Access denied! Too many failed attempts.")

Try this code ❯

❮ Previous: Python Match...Case Next: Python For Loops & Range ❯
Advertisement