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

A closer look at for loops

The for loops in Python exceed the capabilities of for loops in other programming languages. When calling upon iterables such as strings, tuples, lists, sets, or dictionaries, the for loop internally calls the iter to get an iterator. Then, it calls the next method over that iterator to get the actual element in the iterable. It then calls next repeatedly until a StopIteration exception is raised, which it would internally handle and get us out of the loop. The syntax of the for loop is given as follows:

for var in iterable:
statement 1
statement 2
statement n

Let's create a file called for_loops.py, which will explain the basic use of for loops:

In the preceding example, we used the Python range function/method, which helps us implement the traditional for loop that we learnt in other programming languages such as C, C ++, or Java. This might look like for i =0 ;i < 5 ;i ++. The range function in Python takes one mandatory argument and two default ones. The mandatory argument specifies the limit of the iteration and, starting from index 0, returns numbers until it reaches the limit, as seen in lines 3 and 4 of the code. When invoked with two arguments, the first one serves as the starting point of the range and the last one serves as the end point, as is depicted in lines 7 and 8 of our code. Finally, when the range function is invoked with three arguments, the third one serves as the step size, which is equal to one by default. This is depicted in the following output and lines 12 and 13 of the sample code:

Let's take a look at another example of a for loop, which we shall use to iterate over all the iterables that Python defines. This will allow us to explore the real power of for loops. Let's create a file called for_loops_ad.py:

Earlier, we saw how we can read the values from lists, strings, and tuples. In the preceding example, we use the for loop to enumerate over strings, lists, and dictionaries. We learned earlier that the for loop actually invokes the iter method of iterables and then calls the next method for each iteration. This is shown in the following example:

When we iterate over Python dictionaries using a  for loop, by default,  the dictionary keys are returned to us. When we use .items() over dictionaries, it returns us a tuple each time we iterate over it, with the key at 0 th index of the tuple and the value at the first index.
主站蜘蛛池模板: 林芝县| 五指山市| 桂林市| 昭觉县| 灵川县| 贵州省| 如东县| 普安县| 呼伦贝尔市| 大洼县| 荔波县| 绥化市| 梧州市| 墨玉县| 舒城县| 贵定县| 永昌县| 扎兰屯市| 嘉祥县| 达孜县| 沅江市| 襄汾县| 霍州市| 高邑县| 旬阳县| 云南省| 随州市| 渑池县| 云梦县| 儋州市| 屯昌县| 宜昌市| 合江县| 黄梅县| 龙游县| 贵阳市| 南川市| 新余市| 盘山县| 南雄市| 汽车|