Home
Search
Python while Loop ExamplesUnderstand the while-loop. While continues until a terminating condition is met.
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.
Loop notes. Programs spend nearly all their time executing loops. We can rewrite loops for clarity. In a while-loop, we must have an exit condition.
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.
Python program that shows while-loop
i = 0 # While loop condition. while i < 10: print("WHILE:", i) # Add one. i += 1
WHILE: 0 WHILE: 1 WHILE: 2 WHILE: 3 WHILE: 4 WHILE: 5 WHILE: 6 WHILE: 7 WHILE: 8 WHILE: 9
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.
Python program that shows while-else
i = 0 # While loop condition. while i > 100: print(i) # Subtract two. i -= 2 else: print("Loop not entered")
Loop not entered
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.
It stops 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.
Python program that uses break
i = 10 # While greater than zero. while i >= 0: print(i) # End loop if evenly divisible by seven. if i % 7 == 0: break i -= 1
10 9 8 7
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.
Caution A while-true loop can cause serious trouble. If you do not break, it will indefinitely continue.
True The True constant must be specified with an uppercase first letter in Python.
Random This program uses the randint method from the random module. This method returns a number between (and including) 0 and 100.
Random
Python program that uses while True
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.
pass
Python program that uses pass
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.
Sometimes 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.
Python program that uses continue 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.
Program We continue looping until we acquire a random number that is odd. We use a modulo division to find an odd (not even) number.
Python program that uses while loop, gets random numbers
import random while True: # Get random int. n = random.randint(0, 100) print("RANDOM", n) if n % 2 != 0: print("ODD") break
RANDOM 54 RANDOM 64 RANDOM 53 ODD
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.
Python program that uses while, one-line functions
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).
Python program that benchmarks loops
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
A review. In structured programming, blocks have meaning. Loops, like methods, are units that contain commands. They can be called and recalled.
Imperative. Loop constructs, such as while and for (and the range sequence), are critical. Imperatively, step-by-step, they direct the flow of control.
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.
Home
© 2007-2021 sam allen. see site info on the changelog