How to use for statement to create a loop in Python

for statement

The for statement performs a block of code for each element in a sequence or other iterable object.


words = ['this', 'is', 'a', 'test', 'from java2s.com'] 
for word in words: 
    print word 

The code above generates the following result.

or


numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] 
for number in numbers: 
    print number 

The code above generates the following result.

To loop over the keys of a dictionary, you can use a plain for statement, just as you can with sequences:


d = {'x': 1, 'y': 2, 'z': 3} 
for key in d: 
   print key, 'corresponds to', d[key] 

The code above generates the following result.

for loops and sequence unpacking in them:


d = {'x': 1, 'y': 2, 'z': 3} 
for key, value in d.items(): 
   print key, 'corresponds to', value 
   

The code above generates the following result.

Parallel Iteration

iterate over two sequences at the same time.


names = ['anne', 'beth', 'george', 'damon'] 
ages = [12, 45, 32, 102] #  ww w .j  a v  a  2s . c o m

for i in range(len(names)): 
   print names[i], 'is', ages[i], 'years old' 

The code above generates the following result.

else Clauses in Loops

else clause is called if you didn't call break. Let's reuse the example from the preceding section on break:


from math import sqrt 
for n in range(99, 81, -1): 
    root = sqrt(n) #   ww w.  jav a  2s . c o m
    if root == int(root): 
        print n 
        break 
else: 
    print "Didn't find it!" 

The code above generates the following result.

Nested for loops


items = ["aaa", 111, (4, 5), 2.01]        # A set of objects
tests = [(4, 5), 3.14]                    # Keys to search for
# from  w w  w . jav  a 2 s.co  m
for key in tests:                         # For all keys
    for item in items:                    # For all items
        if item == key:                   # Check for match
            print key, "was found" 
            break 
    else: 
        print key, "not found!" 

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules