Iterative Looping

Python supports iterative looping with the for statement, which has the form:

 

for item in sequence :

    loop-group

[else :

    else-group]

 

Iterative looping executes the body of the loop (the loop-group) once for each element in sequence, first setting item to be that element.  If the iteration proceeds to completion without being interrupted by a break statement the else-group will be executed, if specified.

The range([start,] stop[, increment]) helper function generates a sequence of numbers from start (default = 0) to stop, incrementing by increment (default = 1).  Thus range(4) generates the sequence (0, 1, 2, 3).

 

Example: Iterative Looping


# print the first 10 characters

string_1 = “this is a test string”

for i in range(10) : 

    print string_1[i]

 

# print all the characters

string_1 = “this is a test string”

for i in range(len(string_1)) : 

    print string_1[i]

 

# print all the characters (more Python-y)

string_1 = “this is a test string”

for c in string_1 : 

    print c