While the for loop is ideal for iterating over a known sequence or a fixed number of times, the while loop is used when you need to repeat a block of code as long as a certain condition remains True. It's particularly useful when the number of iterations is not known beforehand.
The while Loop
The while loop repeatedly executes a block of code as long as its condition evaluates to True. The condition is checked at the beginning of each iteration.
Syntax:
pythonwhile condition: # Code to execute as long as condition is True statement_1 statement_2 # Make sure to update a variable in the condition to avoid an infinite loop!
Example 1: Simple counter
pythoncount = 0 while count < 5: print(f"Count is {count}") count += 1 # Increment count to eventually make the condition False # Output: # Count is 0 # Count is 1 # Count is 2 # Count is 3 # Count is 4
Important: Without count += 1, this would be an infinite loop, running forever because count < 5 would always be True. Always ensure your while loop has a mechanism to eventually make its condition False.
Example 2: User input validation
pythonpassword = "" while password != "secret": password = input("Enter the password: ") if password != "secret": print("Incorrect password. Try again.") print("Access granted!") # Example interaction: # Enter the password: wrong # Incorrect password. Try again. # Enter the password: password123 # Incorrect password. Try again. # Enter the password: secret # Access granted!
Loop Control Statements
Python provides statements to alter the normal flow of a loop:
-
break: Terminates the loop entirely. The program execution jumps to the statement immediately following the loop.python# Example: Searching for an item items = ["apple", "banana", "cherry", "date"] search_item = "cherry" for item in items: if item == search_item: print(f"Found {search_item}!") break # Exit the loop once found print(f"Checking {item}...") print("Loop finished.") # Output: # Checking apple... # Checking banana... # Found cherry! # Loop finished. -
continue: Skips the rest of the current iteration and moves to the next iteration of the loop. The loop continues, but the code aftercontinuein the current iteration is skipped.python# Example: Print only even numbers for num in range(1, 11): if num % 2 != 0: # If number is odd continue # Skip to the next iteration print(f"{num} is an even number.") # Output: # 2 is an even number. # 4 is an even number. # 6 is an even number. # 8 is an even number. # 10 is an even number.
else Clause with Loops
Both for and while loops can optionally have an else block. This else block is executed only if the loop completes normally (i.e., not terminated by a break statement).
python# Example with for-else (loop completes) for i in range(3): print(f"Loop iteration {i}") else: print("Loop completed without a break.") # Output: # Loop iteration 0 # Loop iteration 1 # Loop iteration 2 # Loop completed without a break. # Example with for-else (loop breaks) for i in range(5): if i == 2: print("Breaking loop at 2.") break print(f"Loop iteration {i}") else: print("This will not be printed because the loop broke.") # Output: # Loop iteration 0 # Loop iteration 1 # Breaking loop at 2.
Understanding while loops and loop control statements allows you to handle situations where iteration counts are dynamic and to fine-tune the behavior of your loops for specific conditions.
Key Takeaways:
whileloops repeat code as long as a condition isTrue.- Always ensure
whileloops have a way to terminate to avoid infinite loops. breakexits the loop entirely.continueskips the rest of the current iteration and proceeds to the next.- The
elseblock of a loop executes if the loop completes without encountering abreak.