官术网_书友最值得收藏!

The for loop

for loops are the most common and, in most cases, the preferred method to perform a task over and over again. Imagine a factory line; for each object on the conveyor belt, a for loop could be used to perform some task on it, such as placing a label on the object. In this manner, multiple for loops can come together in the form of an assembly line, processing each object, until they are ready to be presented to the user.

Much like the rest of Python, the for loop is very simple syntactically, yet powerful. In some languages, a for loop needs to be initialized, have a counter of sorts, and a termination case. Python's for loop is much more dynamic and handles these tasks on its own. These loops contain indented code that is executed line by line. If the object being iterated over still has elements (for example, more items to process) at the end of the indented block, the PVM will position itself at the beginning of the loop and repeat the code again.

The for loop syntax will specify the object to iterate over and what to call each of the elements within the object. Note that the object must be iterable. For example, lists, sets, tuples, and strings are iterable, but an integer is not. In the following example, we can see how a for loop treats strings and lists and helps us iterate over each element in iterable objects:

>>> for character in 'Python':
... print(character)
...
P
y
t
h
o
n
>>> cars = ['Volkswagon', 'Audi', 'BMW']
>>> for car in cars:
... print(car)
...
Volkswagon
Audi
BMW

There are additional, more advanced, ways to call a for loop. The enumerate() function can be used to start an index. This comes in handy when you need to keep track of the index of the current loop. Indexes are incremented at the beginning of the loop. The first object has an index of 0, the second has an index of 1, and so on. The range() function can execute a loop a certain number of times and provide an index:

>>> numbers = [5, 25, 35]
>>> for i, x in enumerate(numbers):
... print('Item', i, 'from the list is:', x)
...
Item 0 from the list is: 5
Item 1 from the list is: 25
Item 2 from the list is: 35
>>> for x in range(0, 100):
... print(x)
0
1
# continues to print 0 to 100 (omitted in an effort to save trees)

主站蜘蛛池模板: 资溪县| 库尔勒市| 东兰县| 娄烦县| 英超| 来宾市| 金山区| 泰和县| 北流市| 双江| 广水市| 吉木乃县| 南江县| 柘荣县| 融水| 巍山| 叙永县| 抚宁县| 偏关县| 汤阴县| 平远县| 上杭县| 开封县| 临清市| 北宁市| 云霄县| 大城县| 田东县| 色达县| 珠海市| 津南区| 湘潭县| 武汉市| 马公市| 响水县| 连云港市| 天祝| 盈江县| 景宁| 麦盖提县| 石首市|