Loops. Statements execute one after another. By default they never repeat. But with loops, control flow is manipulated. With while or for-loops, statements are repeated.
Optimization. Programs spend nearly all their time executing loops. So program optimization often focuses on loops. We can rewrite them to be clearer, faster, better.
While. This loop easily 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.
Less than 10: 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 2 added to it. When it reaches the value 8, the condition in the while evaluates to false.
Finally: And the loop body is not executed any more. The number 10 is never printed.
Based on: Python 3 Python program that shows while-loop i = 0 # While loop condition. while i < 10: print(i) # Add two. i += 2 Output 0 2 4 6 8
For-loop. This loop acts upon a collection of elements, not a min and max. In for, we declare a new variable. And after the in-keyword, we specify the collection we want to loop over.
Note: It is possible to create a new collection, as with range(), immediately for the for-loop to act upon.
And: This makes the for-loop more similar to the syntax forms in other languages.
Python program that shows for-loop names = ["Sarah", "Rakesh", "Markus", "Eli"] # Loop over list. for name in names: print(name) Output Sarah Rakesh Markus Eli
Some notes. In the above program, each of the four names is looped over. We can access, in the for-loop body, the variable name. This is a string variable based on the names list elements.List
Range. This is an immutable sequence. We often use it within for-loops. We can specify the start, the end and a step value (which determines how far each iteration skips ahead).Range
Performance: In my testing, I found that range-based loops are usually the fastest kinds of loops. Range() is efficient.
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") Output 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 Output 10 9 8 7
Reverse. We can loop over any sequence in reverse. We use the reversed() method. This returns a view of the sequence in inverted order. It does not change the original sequence.
Python program that uses reversed # Use reversed on a range. for i in reversed(range(0, 3)): # Display the index. print(i) Output 2 1 0
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 correctly 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 Output 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.DefLambdas
Python 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 Output 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 that uses continue statement list = ["cat", "dog", "panther", "parakeet"] for element in list: # Test for this element. if element == "panther": continue # Display element. print("Pet", element) Output Pet cat Pet dog Pet parakeet
Enumerate. This receives an iterable. It returns each index and the associated value with each index. The result is an object, which has two parts (index, value). Here we use it on a list.
Index: Enumerate here returns an index of 0 for "boat." This makes sense as the value "boat" is the first element in the list.
Python that uses enumerate, list list = ["boat", "car", "plane"] # Call enumerate to loop over indexes and values. for i, v in enumerate(list): print(i, v) Output 0 boat 1 car 2 plane
Benchmark. 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.
And: We find the for-loop syntax is more than two times faster that the while-loop syntax here.
So: You should prefer the for-loop on collections such as lists, when possible.
Python 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()) Results For-loop: 98 ms While-loop: 219 ms
Iter, two arguments. This is a built-in method. With two arguments, iter continually calls the method passed as argument 1. It stops when the second argument, a value, is reached.
Python that uses iter import random elements = ["cat", "dog", "horse", None, "gerbil"] def random_element(): # Return random element from list. return random.choice(elements) # Use iter until a None element is returned. for element in iter(random_element, None): print(element) Output cat horse dog dog gerbil
Iter, one argument. Here iter does something different. It acts upon a collection and returns each element in order. This usage is not often needed—we can just reference the collection.
Python that uses iter, single argument elements = ["cat", "dog", "horse", None, "gerbil"] # Iter returns each element, one after another. for element in iter(elements): print(element) Output cat dog horse None gerbil
Iter, next method. With iter we get an iterator variable. We must call next() on this iterator to use it. Here I call next() to get successive values from a list—no loop is needed.
Python that uses next values = [1, 10, 100, 1000] i = iter(values) # Call the next built-in on an iter. # ... This style of code is not often useful. value = next(i) print(value) value = next(i) print(value) value = next(i) print(value) Output 1 10 100
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.