Loops allow us to run a task repetitively. Let us consider the case where we have a Python list that holds a sequence of data and we are looking for a specific data -- we can run in a loop and iterate over the sequence of data till we find the data that we are looking for. Python provides two types of loops: while loop and for loop.
We begin by providing below a simple representation of the while loop. A while loop runs as long as the specified condition ("loop-condition") is true. Typically, during each round, we need to update the loop-condition so that the loop can terminate after some time. The "else:" clause (the statements following the "else:" in the below provided representation) is run when we quit out of the while loop without using any break statement -- we will learn more about break statements on the next page.
while loop-condition: statement ... else: statement ...
Statements that are within the while-loop form a Python block. Python uses indentation to form a block -- all statements forming a block should have identical indentation (N white-spaces or N-tabs). With Python 3.x, indentation should be identical even in terms of white-spaces and tabs. Thus, if one statement has one tab and the other statement has same number of white-spaces as a tab, then Python 3.x considers it as unequal indentation and leads to an error.
Conceptually, the while loop depends upon a specified condition to determine whether to continue further or to terminate/stop; the condition can be a simple variable or an expression. Thus, for while-loop, it is not uncommon that the variable or expression that specifies if the condition is true, gets modified inside the body of the loop.
Let us go through a simple example to see usage of a while loop. The example uses a counter (variable "index") and increments it to refer to the elements of the list. With each iteration, we increment the value of "index" so that we can refer to the next list element. The loop will automatically terminate after we have iterated through all of the elements. Also, since we don't use the break keyword to exit the loop, Python runs the "else:" block of the "while" clause as well.
listCats = ["tiger", "lion", "mountain lion", "lion", "house-cat", "leopard"] index = 0 totalLionCount = 0 while index < len(listCats): if listCats[index] == "lion": print("Found lion!") totalLionCount += 1 else: print("Searching for lion...") index += 1 else: print("The list contains " + str(totalLionCount) + " lions")
We said earlier that all statements inside the while loop should have same indentation. However, this does not hold true in the above example! The reason for this behavior is that the if and else cases have their own internal blocks. Thus, the statements inside the if and else clauses have an additional level of indentation.
When we run the above example (save in a file, let us say, "while-loop.py"), here is the output:
[user@codingbison]$ python3 while-loop.py Searching for lion... Found lion! Searching for lion... Found lion! Searching for lion... Searching for lion... The list contains 2 lions [user@codingbison]$
We can use a for loop when we have a sequence of items and we are checking if the condition exists for one or more of these items. The for loop traverses through items of a given sequence. At each pass, we assign the next available item of the sequence to the variable.
In the below-provided pseudo-code, we provide two variants of the for loop. At each pass, we assign the next available item in the sequence to the variable. The sequence can be a tuple, list, or dictionary -- accordingly we can keep the element in appropriate format.
for element in sequence: statement ... else: statement ... for (x,y) in sequenceOfTuples: statement ... else: statement ...
Once again, statements within the for loop block form a Python block and each statement should have same level of indentation. Likewise, all statements within the else block should also have same level of indentation.
Let us rewrite the earlier while loop example using a for loop. In the following loop, at each pass the value of the next item in the list is assigned to the "element" variable.
listCats = ["tiger", "lion", "mountain lion", "lion", "house-cat", "leopard"] totalLionCount = 0 for element in listCats: if element == "lion": print("Found lion!") totalLionCount += 1 else: print("Searching for lion...") else: print("The list contains " + str(totalLionCount) + " lions")
Running it also provides the same output as that of the while-loop; we skip it for brevity.
Next, we provide a simple example below to verify the behavior of the for loop with a tuple and a list of tuples. When we use the for loop with "tupWildAnimals", then it prints all the three elements individually. Lastly, we can refer to individual elements of a tuple using the "(x,y)" notation; this is referred to as unpacking of a tuple.
tupPolarBear = ("Polar Bear", "Ursus maritimus", "Arctic") tupArcticFox = ("Arctic Fox", "Alopex lagopus", "Arctic") tupTiger = ("tiger", "Panthera Tigris", "Asia") tupWildAnimals = (tupPolarBear, tupArcticFox, tupTiger) #Try referring to individual elements of a tuple. for element in tupPolarBear: print(element) #Element points to individual tuples. print("") for element in tupWildAnimals: print(element) #(x,y,z) point to elements of each tuple for (x,y,z) in tupWildAnimals: print("\nName: " + x) print("Scientific Name: " + y) print("Location: " + z)
Note that if we pass unequal (more or less) elements in the notation (e.g. "(x,y)" or "(x,y,z,a)") for unpacking, then this will throw an error since each tuple consists of three elements and not two or four! Here is the output when we run this example (saved as file "for-loop-tuple.py").
[user@codingbison]$ python3 for-loop-tuple.py Polar Bear Ursus maritimus Arctic ('Polar Bear', 'Ursus maritimus', 'Arctic') ('Arctic Fox', 'Alopex lagopus', 'Arctic') ('tiger', 'Panthera Tigris', 'Asia') Name: Polar Bear Scientific Name: Ursus maritimus Location: Arctic Name: Arctic Fox Scientific Name: Alopex lagopus Location: Arctic Name: tiger Scientific Name: Panthera Tigris Location: Asia [user@codingbison]$
After having seen the usage of for loops with lists and tuples (and lists consisting of tuples), let us look at using the for loop for a dictionary. Once again, we can use a for loop to selectively loop through keys, values, or key/value pairs of a dictionary.
// Loop through dictionary keys. for keys in sequenceDictonary.keys(): statement ... else: statement ... // Loop through dictionary values. for values in sequenceDictionary.values(): statement ... else: statement ... // Loop through dictionary key/value pairs. for (keys, values) in sequenceDictionary.items(): statement ... else: statement ...
Next, we provide a simple example that contains a dictionary holding animal names and their scientific names. We use the for loop to iterate through keys, values, and key/value pairs. Note that we need to use keys(), values(), and items() methods to get the list of keys, values, and key/value pairs for a dictionary.
dictWildAnimals = {} dictWildAnimals["Polar Bear"] = "Ursus maritimus" dictWildAnimals["Arctic Fox"] = "Alopex lagopus" dictWildAnimals["tiger"] = "Panthera Tigris" #Try referring to elements of a dictionary. print("Dictionary elements:") for element in dictWildAnimals: print(element) #Try referring to keys of a dictionary. print("\nDictionary keys:") for key in dictWildAnimals.keys(): print(key) #Try referring to values stored in a dictionary. print("\nDictionary values:") for value in dictWildAnimals.values(): print(value) #Try referring to key/value pairs present in the dictionary. print("\nDictionary key/value pairs:") for (key, value) in dictWildAnimals.items(): print("Key: " + key + "\t Value: " + value)
We save the example in a file "for-loop-dictionary.py" and run it -- we provide the output below.
[user@codingbison]$ python3 for-loop-dictionary.py Dictionary elements: tiger Arctic Fox Polar Bear Dictionary keys: tiger Arctic Fox Polar Bear Dictionary values: Panthera Tigris Alopex lagopus Ursus maritimus Dictionary key/value pairs: Key: tiger Value: Panthera Tigris Key: Arctic Fox Value: Alopex lagopus Key: Polar Bear Value: Ursus maritimus [user@codingbison]$
Note that using the for loop with a dictionary ("for x in dict") without specifying any methods (like keys(), values(), or items() as in "for x in dict.keys()") returns the keys of the dictionary.