On this page

While Loops

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

What a While Loop Is​

A while loop repeats a block of code as long as a condition remains True. Unlike a for loop, which iterates over a sequence, a while loop continues running until its condition becomes False. This makes it useful for situations where you do not know in advance how many repetitions are needed.

The structure is:


while condition:

    # repeated block

Python evaluates the condition before each iteration. If the condition is True, the loop runs; if it is False, the loop stops.

Basic While Loop Example​


count = 1



while count <= 5:

    print(count)

    count += 1

This loop prints numbers from 1 to 5. The variable count increases each time, eventually making the condition False and ending the loop.

The Importance of Updating the Condition​

Every while loop must change something inside the loop so that the condition eventually becomes False. If not, the loop will run forever.

Example of an infinite loop (do not run):


while True:

    print("This never ends")

Infinite loops are sometimes intentional, but beginners should avoid them until they understand loop control.

Using While Loops for User Input​

While loops are ideal for repeated input until the user provides valid data.


name = ""



while not name:

    name = input("Enter your name: ")



print("Hello,", name)

The loop continues until the user types a non‑empty string.

Sentinel-Controlled Loops​

A sentinel value is a special input that signals the loop to stop.


total = 0

value = input("Enter a number (or 'q' to quit): ")



while value != "q":

    total += float(value)

    value = input("Enter a number (or 'q' to quit): ")



print("Total:", total)

This pattern is common in data entry and menu-driven programs.

Loop Control with break and continue​

break​

Stops the loop immediately.


while True:

    text = input("Type 'stop' to exit: ")

    if text == "stop":

        break

continue​

Skips the rest of the loop block and starts the next iteration.


for n in range(5):

    if n == 2:

        continue

    print(n)

Although shown here with a for loop, continue works the same way in while loops.

While vs. For Loops​

Use a for loop when you know the number of iterations or when iterating over a sequence.

Use a while loop when repetition depends on a condition that changes over time, especially with user input or unpredictable events.

Why While Loops Matter​

While loops allow you to build programs that react dynamically to conditions, user choices, and changing data. They are essential for input validation, menu systems, simulations, and any task where repetition continues until a specific condition is met.

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

For Loops

Next

Loop Control