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.
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.
while
-loop continues as long as the variable "i" has a value less than 10 when the statement is encountered.i = 0 # While loop condition. while i < 10: print("WHILE:", i) # Add one. i += 1WHILE: 0 WHILE: 1 WHILE: 2 WHILE: 3 WHILE: 4 WHILE: 5 WHILE: 6 WHILE: 7 WHILE: 8 WHILE: 9
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.
while
-loop makes no difference.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 -= 110 9 8 7
Sometimes a while
-loop is never entered. The initial condition evaluates to false. In this example, the variable "i" is set to 0.
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
-trueA 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.
while-true
loop can cause serious trouble. If you do not break
, it will indefinitely continue.import random # A while-true loop. while True: n = random.randint(0, 100) print(n) # Break on even random number. if n % 2 == 0: break41 13 99 18
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.
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. pass0 2 2 3
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.
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
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.
import random while True: # Get random int. n = random.randint(0, 100) print("RANDOM", n) if n % 2 != 0: print("ODD") breakRANDOM 54 RANDOM 64 RANDOM 53 ODD
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.
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
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.
for
-loop. We loop over the strings, and sum their lengths.while
-loop. The logic is the same as version 1 of the code.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
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.