Python While Loop: Mastering Iteration for AI & ML
Learn how to use Python's `while` loop for dynamic iteration in AI and Machine Learning. Master conditional execution for your projects.
2.4 Python While Loop
The while
loop in Python is a fundamental control flow statement used to repeatedly execute a block of code as long as a specified condition remains True
. This makes it particularly useful when the number of iterations is not known in advance and depends on dynamic conditions.
Syntax of a while
Loop
The basic structure of a while
loop is as follows:
while condition:
# Code block to be executed
# This block runs as long as 'condition' is True
condition
: A boolean expression that is evaluated before each iteration. If the condition evaluates toTrue
, the code block inside the loop is executed. If it evaluates toFalse
, the loop terminates, and program execution continues with the statement immediately following thewhile
loop.
How the while
Loop Works – Step-by-Step
- Evaluate the
condition
: Python checks if thecondition
isTrue
orFalse
. - Execute Code Block: If the
condition
isTrue
, the code block within the loop is executed. - Repeat: After executing the code block, Python returns to Step 1 to re-evaluate the
condition
. - Terminate: If the
condition
isFalse
, the loop stops, and execution proceeds to the next statement after the loop.
Example 1: Simple Counter Loop
This example demonstrates a while
loop that increments a counter until a specific value is reached.
counter = 1
while counter <= 3:
print(f"Count: {counter}")
counter += 1
print("Loop completed.")
Output:
Count: 1
Count: 2
Count: 3
Loop completed.
In this example, the loop continues as long as counter
is less than or equal to 3. Inside the loop, the current counter
value is printed, and then counter
is incremented by 1.
Example 2: Wait for Non-Numeric Input
This loop continues to prompt the user for input as long as the input consists only of numeric characters. It stops when the user enters something that is not a number.
user_input = "0" # Initialize with a numeric string to enter the loop
while user_input.isnumeric():
user_input = input("Enter a number (or a word to stop): ")
if user_input.isnumeric():
print(f"You entered: {user_input}")
print("Loop stopped. Non-numeric input detected.")
Sample Output:
Enter a number (or a word to stop): 45
You entered: 45
Enter a number (or a word to stop): 100
You entered: 100
Enter a number (or a word to stop): hello
Loop stopped. Non-numeric input detected.
The loop utilizes the isnumeric()
string method to check if the entered input contains only digits.
Infinite while
Loop in Python
An infinite loop occurs if the condition
in a while
loop never evaluates to False
. These loops will run indefinitely unless explicitly terminated (e.g., by the user interrupting the program, typically with Ctrl+C
). While often an error, infinite loops can be useful in specific scenarios like server processes or waiting for events.
while True:
command = input("Type 'exit' to stop: ")
if command.lower() == "exit":
break # Exit the loop when the command is 'exit'
print(f"You said: {command}")
Sample Output:
Type 'exit' to stop: hey
You said: hey
Type 'exit' to stop: hello there
You said: hello there
Type 'exit' to stop: exit
In this case, while True:
creates a condition that is always True
. The break
statement is crucial for providing an exit mechanism based on user input.
while
Loop with else
Block
Python supports an optional else
block that can be used with while
loops. The code within the else
block is executed only when the loop terminates naturally (i.e., the condition becomes False
), and not if the loop is exited prematurely using a break
statement.
attempts = 0
while attempts < 3:
print(f"Attempt {attempts + 1}")
attempts += 1
else:
print("All attempts done.")
Output:
Attempt 1
Attempt 2
Attempt 3
All attempts done.
Here, the else
block executes because the loop condition attempts < 3
eventually becomes False
. If a break
statement were encountered within the loop, the else
block would be skipped.
One-Liner while
Statement
For very simple conditions, a while
loop can be written on a single line. However, this is generally discouraged for readability unless the operation is trivial.
flag = False
while flag: print("This won't be printed")
print("Exited loop")
Output:
Exited loop
In this example, since flag
is initialized to False
, the condition is immediately false, and the loop body is never executed. If flag
were set to True
, this would result in an infinite loop unless an external mechanism (like Ctrl+C
) interrupted it.
Key Points to Remember
- Prevent Infinite Loops: Always ensure that the condition controlling the
while
loop will eventually becomeFalse
. Failure to do so will result in an infinite loop, which can freeze your program. break
Statement: Use thebreak
statement to exit the loop immediately, regardless of the loop's condition. This is useful for stopping the loop based on a specific event or condition occurring within the loop's body.continue
Statement: Use thecontinue
statement to skip the rest of the current iteration and proceed directly to the next evaluation of the loop's condition. This is helpful for bypassing certain steps under specific circumstances.
The while
loop is a versatile tool in Python for managing repetitive tasks where the number of iterations is not predetermined. It offers flexibility and control over program flow based on dynamic conditions.
Python For Loop: Master Iteration for ML & AI
Learn the Python 'for' loop for efficient iteration over lists, strings, and dictionaries. Essential for data science, machine learning, and AI development.
Python continue Statement: Skip Iterations Efficiently
Master the Python `continue` statement to skip current loop iterations & efficiently process data, ideal for filtering in AI/ML workflows.