Book Image

The Python Apprentice

By : Robert Smallshire, Austin Bingham
Book Image

The Python Apprentice

By: Robert Smallshire, Austin Bingham

Overview of this book

Experienced programmers want to know how to enhance their craft and we want to help them start as apprentices with Python. We know that before mastering Python you need to learn the culture and the tools to become a productive member of any Python project. Our goal with this book is to give you a practical and thorough introduction to Python programming, providing you with the insight and technical craftsmanship you need to be a productive member of any Python project. Python is a big language, and it’s not our intention with this book to cover everything there is to know. We just want to make sure that you, as the developer, know the tools, basic idioms and of course the ins and outs of the language, the standard library and other modules to be able to jump into most projects.
Table of Contents (21 chapters)
Title Page
Credits
About the Authors
www.PacktPub.com
Customer Feedback
Preface
12
Afterword – Just the Beginning

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