The For-loops – iterating over series of items

Now that we have the tools to make some interesting data structures, we'll look
at Python's other type of loop construct, the for-loop. The for-loops in Python correspond to what are called for-each loops in many other programming languages. They request items one-by-one from a collection – or more strictly from an iterable series (but more of that later) – and assign them in turn to the a variable we specify. Let's create a list collection, and use a for-loop to iterate over it, remembering to indent the code within the for-loop by four spaces:

>>> cities = ["London", "New York", "Paris", "Oslo", "Helsinki"]
>>> for city in cities:
... print(city)
...
London
New York
Paris
Oslo
Helsinki

So iterating over a list yields the items one-by-one. If you iterate over a dictionary, you get just the keys in seemingly random order, which can then be used within the for-loop body to retrieve the corresponding values. Let's define a dictionary which maps color name strings to hexadecimal integer color codes stored as integers:

>>> colors = {'crimson': 0xdc143c, 'coral': 0xff7f50, 
'teal': 0x008080}

>>> for color in colors:
... print(color, colors[color])
...
coral 16744272
crimson 14423100
teal 32896

Here we use the ability of the built-in print() function to accept multiple arguments, passing the key and the value for each color separately. See also how the color codes returned to us are in decimal.

Now, before we put some of what we've learned together into a useful program, practice exiting the Python REPL with Ctrl+Z on Windows or Ctrl+D on Mac or Linux.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset