1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Controlling the Flow

From , former About.com Guide

6 of 7

FOR Loops - Part 1

We saw in our discussion of variables and datatypes that Python, and programming in general, does a lot with series and sequences of data. Often it is faster or easier if the computer can perform a certain action a set number of times, perhaps based on a certain number of items. The 'for' loop allows this kind of iteration.

The syntax of the 'for' loop follows this template:

for <counter variable> in <range list>:
    <action to be performed>

The counter variable can be any variable. It simply serves as a variable into which Python can put each item of the range list in turn. It can be, and often is, referenced in the command part of the loop.

The range list can be anything: numeric literal, string literal, list, tuple, dictionary, or any combination thereof. What matters is that you access the items in the correct way. Some examples follow below.

prime = [1,3,5,7,9,11]
for n in prime:
     print n
output: 1
3
5
7
9
11
vornamen = ['Bill', 'John', 'Luke', 'Ricky']
for name in vornamen:
     print name
output:
Bill
John
Luke
Ricky
info = {
     "producer" : "Kubrick",
     "title" : "Dr Strangelove",
     "phone call" : "Hello, Dmitri"
     }

for key in info:
     print key
     print info[key]
     print "\n"
output:
phone call
Hello, Dmitri

producer
Kubrick

title
Dr Strangelove

Explore Python
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.