A while True loop in Python runs indefinitely until a break statement exits it. This pattern is useful whenever you cannot know in advance how many iterations a loop needs — for instance, when repeatedly asking a user for valid input or running a menu-driven program until the user chooses to quit.

What is a while True loop?

A regular while loop runs as long as its condition is true:

while count < 5:
    print(count)
    count += 1

A while True loop uses the literal True as its condition — which is always true — so the loop never stops naturally. It is the programmer's responsibility to include a break statement inside the loop to exit when the right condition is met:

while True:
    name = input("Enter your name: ")
    if name != "":
        break   # exit the loop when a non-empty name is given
print(f"Hello, {name}!")

Without the break, this loop would run forever — an infinite loop, which is almost always a bug.

When should you use while True rather than a regular while loop?

while True is the cleaner choice when the exit condition can only be checked partway through the loop body, after some computation has happened. Two classic cases are:

  1. Input validation — you need to get valid input from the user. The check happens after the input is read, so you cannot put the condition at the top of the while without reading input twice.
  2. Menu-driven programs — show a menu, take an action, repeat until the user chooses to quit.

A regular while loop is cleaner when you know the number of iterations in advance or the condition can be checked before the first iteration.

How to write an input validation loop step by step

A common KS3 task: keep asking for a number between 1 and 10 until the user enters a valid one.

  1. Start the loop with while True:
  2. Ask for input and convert it to the required type.
  3. Check whether the input meets the requirement.
  4. If valid, break out of the loop.
  5. If invalid, print an error and let the loop continue.
while True:
    user_input = input("Enter a number between 1 and 10: ")
    
    if user_input.isdigit():          # check it is a whole number
        number = int(user_input)
        if 1 <= number <= 10:         # check it is in range
            break                     # valid — exit the loop
    
    print("Invalid. Please try again.")

print(f"You entered: {number}")

Trace through the loop with inputs 0, abc, 7:

Iteration Input isdigit()? In range? Action
1 0 Yes No (0 < 1) Print error, repeat
2 abc No — Print error, repeat
3 7 Yes Yes break — exit loop

After the loop, number holds 7 and execution continues.

How to write a menu-driven program

A menu loop shows options, reads the user's choice, carries out the action, then repeats. break exits when the user chooses to quit.

while True:
    print("\n--- Main Menu ---")
    print("1. Say hello")
    print("2. Calculate square")
    print("3. Quit")
    
    choice = input("Choose an option: ")
    
    if choice == "1":
        print("Hello!")
    elif choice == "2":
        n = float(input("Enter a number: "))
        print(f"Square: {n ** 2}")
    elif choice == "3":
        print("Goodbye!")
        break             # exit the loop
    else:
        print("Invalid choice, try again.")

The loop keeps running until the user enters 3. Each iteration is independent: the user sees the menu, makes a choice, the action runs, and the next iteration starts.

What does the continue statement do?

Alongside break, Python has continue — it skips the rest of the current iteration and jumps back to the start of the loop. It is useful for skipping unwanted inputs without exiting the loop entirely:

numbers = [1, -2, 3, -4, 5]
total = 0
for n in numbers:
    if n < 0:
        continue   # skip negative numbers — do not add to total
    total += n
print(f"Sum of positives: {total}")   # Output: Sum of positives: 9
Statement Effect
break Exit the loop immediately
continue Skip to the next iteration
Neither Complete the current iteration and continue normally

Frequently asked questions

Why is an infinite loop usually a bug?

An infinite loop runs forever, consuming CPU time and preventing any other code from running. In a simple script this crashes the program (or forces the user to terminate it with Ctrl+C); in a web server or real-time system it can cause the entire service to become unresponsive. while True is not a bug — it is a valid pattern — but every while True loop must contain a reachable break (or another exit mechanism) to avoid becoming an infinite loop.

Can I use while True with a for loop inside?

Yes. break and continue always affect only the innermost loop they appear in. A break inside a for loop that is nested inside a while True loop will exit the for loop, not the while True loop. If you want to exit the outer loop from inside the inner loop, you typically use a flag variable:

found = False
while True:
    for item in collection:
        if condition(item):
            found = True
            break   # exits the for loop
    if found:
        break       # now exits the while loop

What happens if I forget the break in a while True loop?

The loop runs indefinitely. Python does not detect infinite loops automatically — it cannot know whether you intended the loop to run forever (e.g., a server listening for connections) or forgot a break. If your program seems to hang and produce no output, an unbroken while True loop is one of the first things to check. In IDLE or a terminal, Ctrl+C sends a KeyboardInterrupt to stop the program.

Is while True faster than using a condition in while?

In practice, the difference is negligible for KS3 programs. Python evaluates True as a constant and the loop overhead is the same as any other while loop. Choose while True when it makes the logic clearer (exit mid-loop), and a regular while condition: when the exit condition is naturally known at the top of the loop.


Work through Python loop exercises with immediate feedback from Professor Turing at aitutors.me.