Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What Does while true do in Python?
The while True loop is a fundamental control structure in Python that creates an infinite loop. Unlike regular while loops that check a condition, while True runs indefinitely until explicitly terminated with a break statement or program interruption.
Syntax
while True:
# Code block to be executed repeatedly
if condition:
break # Exit the loop when condition is met
The keyword while is followed by the condition True, which always evaluates to True. This creates a loop that continues indefinitely until an explicit exit mechanism is used.
Basic Example
Here's how a while True loop works with a counter ?
count = 0
while True:
count += 1
print(count)
if count >= 5:
break
1 2 3 4 5
In this example ?
The loop starts with
count = 0Each iteration increments
countby 1The
breakstatement exits the loop when count reaches 5
User Input Validation
A common use case is validating user input until a correct response is provided ?
while True:
user_input = input("Enter 'yes' or 'no': ")
if user_input.lower() == "yes":
print("You chose yes!")
break
elif user_input.lower() == "no":
print("You chose no!")
break
else:
print("Invalid input. Please try again.")
Enter 'yes' or 'no': maybe Invalid input. Please try again. Enter 'yes' or 'no': yes You chose yes!
Menu System Example
Here's a practical example of a simple menu system ?
while True:
print("\n=== Menu ===")
print("1. Say Hello")
print("2. Calculate Square")
print("3. Exit")
choice = input("Choose an option (1-3): ")
if choice == "1":
print("Hello, World!")
elif choice == "2":
num = int(input("Enter a number: "))
print(f"Square of {num} is {num**2}")
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice. Try again.")
=== Menu === 1. Say Hello 2. Calculate Square 3. Exit Choose an option (1-3): 1 Hello, World! === Menu === 1. Say Hello 2. Calculate Square 3. Exit Choose an option (1-3): 3 Goodbye!
Important Considerations
Always include an exit condition: Without a
breakstatement or exit mechanism, the loop will run foreverResource consumption: Infinite loops can consume CPU and memory if not properly controlled
User experience: Provide clear instructions and validation messages
Comparison with Regular While Loops
| Loop Type | Condition | Best For |
|---|---|---|
while condition: |
Dynamic condition | Known termination criteria |
while True: |
Always True | Complex exit conditions, user interaction |
Conclusion
The while True loop is essential for scenarios requiring indefinite repetition with complex exit conditions. Always include proper exit mechanisms to prevent infinite execution and ensure responsive user interaction.
