Loops are an integral part of any programming language and one of your most powerful assets to manipulate control flow. Loops allow you to repeat actions any number of times with very concise syntax. If loops didn't exist, you would have to copy, paste, and possibly adjust all the statements you would want repeated. Python provides two structures that support looping, the for loop and the while loop.
Unlike other programming languages, where a for loop is often step-based, a for loop in Python iterates through the elements of an iterable object.
An iterable is any object capable of returning its members one at a time, permitting it to be iterated over.
An iterable object is any object that supports the __getitem__() or __iter__() method, which are the methods that are called when you try to iterate over an object.
>>> '__iter__' in dir(str)
|
True
|
>>> '__iter__' in dir(int)
|
False
|
The dir(obj) function returns the names of all methods defined by obj. In the code above we check whether the str and int objects support the __iter__() method. As you can see, strings are iterable objects, while integers are not. In fact, strings are the only iterables we've discussed thus far.
So how does one loop through an iterable using a for loop? The syntax is actually very intuitive.
Here, member is the object that the iterable returns at every iteration of the loop. The indented statement is the code that is ran every iteration. The reference to member can be used in the statement, and as mentioned, is updated to the next member every iteration.
For example, when iterating over the object , member will first be a reference to , then to , and in the final iteration to .
|
|
iterable = "abc"
for member in iterable: print(member)
|
a b c
|
|
loops also support a manual break with the keyword, usually used in combination with a conditional statement.
loops can also be combined with the keyword. The block is only executed when the loop is completely exhausted. In other words, when is not triggered prematurely. If there's no conditional break present in the for loop, an else-statement can still be used for readability.
|
|
string = "Hello, world! How have you been?"
for char in string: print(char, end="")
if char in "!?.": break else: print("No sentence.")
|
Hello, world!
|
|
loops also support the keyword. allows you to jump to the next iteration of the loop when it is triggered. When a conditional statement containing is triggered, all subsequent code will be skipped over.
|
|
for char in "abcDEF": if not char.isupper(): continue print(char)
|
D E F
|
|
Now that we have seen the syntax of a for loop, we need to introduce more iterable objects. For now, we'll do so using functions that return iterable objects. The function is the most common iterable generating function and mimicks a traditional loop.
The function returns an iterable exclusive range from start to stop. The start argument is optional, if left undefined, the range will always start at . An additional, also optional argument, is step, it defines the increment between members of the range, the default is . All arguments of the function have to be of type .
|
|
for i in range(5): print(i)
|
0 1 2 3 4
|
|
The function returns an iterable exclusive range from start to the length of the corresponding iterable, and the iterable itself. The default value for the optional start argument is . Note that we loop through two members at a time now, the member of the range and the member of the iterable . allows you to loop over an iterable and a potentially corresponding number or index.
|
|
for i, char in enumerate("abc"): print(i, char)
|
0 a 1 b 2 c
|
|
The function returns a combined iterable formed by the iterators referenced in its arguments. Like , we can now loop through multiple members per iteration. Only iterables of the same length can be combined using .
|
|
seq = zip("abc", "def", "ghi")
for c1, c2, c3 in seq: print(c1, c2, c3)
|
a d g b e h c f i
|
|
In the next chapter, we will see more iterable datatypes.