while Loop Examples
This page was last reviewed on Mar 1, 2024.
Dot Net Perls
While. Usually in Python the for-loop is the clearest. But for an infinite loop, or a loop with no simple endpoint, a while-loop is a good choice.
In Python programs, we can rewrite loops for clarity. While loops often work best when no end point is known before entering the loop. A break can stop the loop.
First example. The while-loop passes over a range of numbers. In it, we use an iteration variable named "i." On the first line of the while-loop, we specify a condition.
Info This while-loop continues as long as the variable "i" has a value less than 10 when the statement is encountered.
And After each iteration, the variable "i" has 1 added to it. When it reaches the value 10, the loop stops—10 is never printed.
i = 0 # While loop condition. while i < 10: print("WHILE:", i) # Add one. i += 1
Break. In structural programming, scope is key. In a loop, we use the break keyword to "break" out of the enclosing loop scope. The loop terminates.
And No further iterations execute. The condition in the while-loop makes no difference.
Here The while-loop keeps iterating until the value of "i" is evenly divisible by 7. Then we break.
i = 10 # While greater than or equal to zero. while i >= 0: print(i) # End loop if evenly divisible by seven. if i % 7 == 0: break i -= 1
10 9 8 7
Else. Sometimes a while-loop is never entered. The initial condition evaluates to false. In this example, the variable "i" is set to 0.
But The loop only executes when it is greater than 100. The statements within the while are not reached.
So We can use the else-statement, after the main part of a while-loop, to catch these situations.
i = 0 # While loop condition. while i > 100: print(i) # Subtract two. i -= 2 else: print("Loop not entered")
Loop not entered
While-true. A while-true loop infinitely continues unless stopped. We use break to terminate such a loop. A while-true loop is sometimes easier to understand than other loops.
Warning A while-true loop can cause serious trouble. If you do not break, it will indefinitely continue.
Note The True constant must be specified with an uppercase first letter in Python.
Info This program uses the randint method from the random module. This method returns a number between (and including) 0 and 100.
import random # A while-true loop. while True: n = random.randint(0, 100) print(n) # Break on even random number. if n % 2 == 0: break
41 13 99 18
Pass. This does nothing. Sometimes a loop must continue until its expression evaluates to false. The body is not needed. In C-like languages, a semicolon would be used for an empty line.
But In Python, we use no semicolons. Instead, we use the pass statement to have an empty loop body.
Tip The pass statement can also be used in def-method bodies, or lambda expressions.
import random def m(): # Get random number. n = random.randint(0, 3) print(n) # Return true if number is less than 3. return n <= 2 # Call method until it returns false. while m(): # Do nothing in the loop. pass
0 2 2 3
Continue. This does not terminate a loop. It just stops the current iteration of one. The loop keeps going, but no statements in that same iteration are executed.
Detail It is easier to use a continue statement instead of an else statement. In some blocks, this makes code easier to read.
And The continue statement can help improve loop symmetry in loops that also use the break statement.
list = ["cat", "dog", "panther", "parakeet"] i = 0 while i < len(list): element = list[i] i += 1 # Test for this element. if element == "panther": continue # Display element. print("Pet", element)
Pet cat Pet dog Pet parakeet
While random. The while-True loop has some uses. Consider a situation where we want to get random numbers until one matches a condition. A while-loop is good here.
Here We continue looping until we acquire a random number that is odd. We use a modulo division to find an odd (not even) number.
import random while True: # Get random int. n = random.randint(0, 100) print("RANDOM", n) if n % 2 != 0: print("ODD") break
One-line, functions. We can use functions for the condition, and body, of while-loops. And we can collapse the while-loop down to just 1 syntax line in some cases too.
Here The valid_number and handle_number functions control both parts of the while-loop. The text "Hello friend" is printed.
def valid_number(i): return i <= 3 def handle_number(i): print(f"Hello friend {i}") # Next number. return i + 1 i = 0 # Use a while-True loop on one line. while valid_number(i): i = handle_number(i)
Hello friend 0 Hello friend 1 Hello friend 2 Hello friend 3
Benchmark, for, while. A list can be looped over with for or while. The for-loop uses fewer statements. In this benchmark, we test a loop that sums the lengths of elements in a string list.
Version 1 This version of the code uses a for-loop. We loop over the strings, and sum their lengths.
Version 2 Here we use the while-loop. The logic is the same as version 1 of the code.
Result The for-loop syntax faster that the while-loop syntax here. Prefer the for-loop on collections such as lists (when possible).
import time names = ["San Jose", "Denver", "New York", "Phoenix"] print(time.time()) # Version 1: for-loop. i = 0 while i < 100000: count = 0 # Loop. for name in names: count += len(name) i = i + 1 print(time.time()) # Version 2: while-loop. i = 0 while i < 100000: count = 0 # Loop. x = 0 while x < len(names): count += len(names[x]) x = x + 1 i = i + 1 print(time.time())
For-loop: 98 ms While-loop: 219 ms
Loop comparison. For most methods, the for-loop is best. A for-loop over a range has the lowest chance of a programming error. And it is easiest to maintain and read.
The while-loop is useful in programs that have loops with unknown end points. Loop constructs, such as while and for, direct the flow of control.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Mar 1, 2024 (edit).
© 2007-2024 Sam Allen.