The for statement provides a convenient way to create a loop that does not run the
risk of executing forever.
Here is an example that uses for to display the numbers from 1 to 10:
# another way to display the numbers from 1 to 10
for x in range(1,11):
print x
Here, range(1,11) represents every number between 1 and 10. When used in a for statement, it
tells Python to execute the loop once for every number in the range, assigning the number to x as it
does so. In this example, when the loop is executed for the first time, x has the value 1. The second
time through, x has the value 2, and so on.
As a general rule, range(a,b) includes all integers
from a to b - 1. It does not include b.
range(1,11) is an example of a list. The for statement can also be used effectively
with a variety of other lists and dictionaries. For more information on lists and dictionaries, see
the sections on Lists and Dictionaries.