- Hands-On Penetration Testing with Python
- Furqan Khan
- 452字
- 2021-07-02 14:13:54
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:

- Intel Galileo Essentials
- OpenDaylight Cookbook
- INSTANT OpenCV Starter
- Learning RabbitMQ
- Getting Started with SQL Server 2012 Cube Development
- 深入分布式緩存:從原理到實踐
- Geospatial Development By Example with Python
- Building Serverless Web Applications
- Learning Jakarta Struts 1.2: a concise and practical tutorial
- AI自動化測試:技術原理、平臺搭建與工程實踐
- 黑莓(BlackBerry)開發從入門到精通
- 視窗軟件設計和開發自動化:可視化D++語言
- 從零開始學算法:基于Python
- Less Web Development Cookbook
- 零基礎C語言學習筆記