Python Programming Exercises,
Gently Explained
75
Python’s for loops can iterate over lists of any values. For example, enter the following into the
interactive shell:
>>> for i in ['Alice', 'Bob', 'Carol']:
... print('Hello ' + i)
...
Hello
Alice
Hello Bob
Hello Carol
What a for loop does is iterate over a sequence of values. The following
interactive shell
example is the equivalent for i in range(4):
>>> for i in [0, 1, 2, 3]:
... print(i)
...
0
1
2
3
In this case, we explicitly typed out the integers to iterate in a list rather than use the more
convenient range(4). But they produce identical results. And explicitly typing
out the integers in a
list becomes prohibitively long for large ranges such as range(1000).
Dostları ilə paylaş: