0
0
Pythonprogramming~5 mins

while True pattern in Python

Choose your learning style9 modes available
Introduction

The while True pattern lets a program keep doing something over and over until you tell it to stop. It is useful when you don't know how many times you need to repeat a task.

When you want to keep asking a user for input until they give a valid answer.
When you want a program to run forever until you stop it manually.
When you want to keep trying an action until it succeeds.
When you want to create a menu that keeps showing until the user chooses to exit.
Syntax
Python
while True:
    # code to repeat
    if some_condition:
        break

The loop runs forever because True is always true.

You use break inside the loop to stop it when needed.

Examples
This prints "Hello" once and then stops the loop immediately.
Python
while True:
    print("Hello")
    break
This keeps asking the user to type something until they type 'exit'.
Python
while True:
    answer = input("Type 'exit' to stop: ")
    if answer == 'exit':
        break
    print(f"You typed: {answer}")
Sample Program

This program keeps asking the user to enter a number. If the user types 'stop', it says goodbye and ends. If the user types a number, it shows it back. If the input is not a number, it asks again.

Python
while True:
    number = input("Enter a number (or 'stop' to end): ")
    if number == 'stop':
        print("Goodbye!")
        break
    if number.isdigit():
        print(f"You entered: {number}")
    else:
        print("That's not a number. Try again.")
OutputSuccess
Important Notes

Always make sure there is a break inside the while True loop to avoid an infinite loop that never stops.

You can use continue to skip to the next loop cycle if needed.

Summary

while True creates a loop that runs forever until stopped.

Use break inside the loop to stop it when a condition is met.

This pattern is great when you don't know how many times you need to repeat something.