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, ...

Get Hands-On Penetration Testing with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.