for loop is one of the most used loops in many computer languages. The following flow diagram demonstrates how a loop works. Usually, we start with an initial value. Then, we test a condition. If the condition is false, the program stops. Otherwise, we execute a set of commands:
The simplest example is given as follows:
>>>for i in range(1,5): print i
Running these two lines will print 1, 2, 3, and 4. We have to be careful with the
range() function since the last number, 5, will not be printed in Python. Thus, if we intend to print from 1 to n, we have to use the following code:
>>>n=10 >>>for i in range(1,n+1): print ...