- Learn Python by Building Data Science Applications
- Philipp Kats David Katz
- 430字
- 2021-06-24 13:06:11
The for loop
The for loop is the classical form of the loop—it literally goes over an iterable (collection of values) and performs the same computation for each value, consecutively. The code within the loop may or may not be using the value for which it is computed.
For example, if we just need to run some specific code N times, we can run the loop over the range object that contains N values. Consider the following example:
>>> for i in range(3):
>>> print(i)
0
1
2
Here, we execute a built-in range function (which we discussed in Chapter 3, Functions) and run a loop, printing each element in this loop.
Any other iterable would suffice as well, including strings, sets, lists, tuples, dictionaries, and generators. All the code in the scope of the loop will be repeated as many times as there are elements in the iterable. In the following code, we loop through the characters in a string, printing each of them:
>>> for char in 'Jack':
>>> print(char)
J
a
c
k
Loops require indentation—just like functions. In contrast to functions, however, variables assigned in the loop (the last value they were assigned to), will be accessible from the outside of this indentation. The looping variable ( el in the first example, and char in the second) can be named as you see fit.
In fact, we can pass more than one value using unpacking. Here is one example. We're iterating over a dictionary, using its items method. In the first line of the loop, we can define two variables, the first representing the key, and the second the value. Once defined, both variables can be used in the code—in this case, printed. If we were to state one argument instead, it would be assigned a tuple of key-value pairs:
>>> person = {
'name':'Jim',
'surname':'Hockins'
}
>>> for k, v in person.items():
print(k, ':', v)
name : Jim
surname : Hockins
As a result, key and value are printed for each pair in the dictionary—name : Jim.
The power of loops can be expanded, leveraging built-in additional tools. Let's take a look.