"for" Statement for Iterative Execution

This section provides a quick introduction of 'for' statement, which executes a block of sub-statements repeatedly while the given condition is valid.

What Is "for" Statement? A "for" statement is a compound statement that iterates over the elements of a sequence and executes a block of sub-statements for each iteration.

A "for" statements must have a "for" clause followed by an optional "else" clause:

```for target in iterable:
sub-statement
sub-statement
...
else:
sub-statement
sub-statement
...
```

Logically, you can replace a "for" statement with the following code using a "while" statement:

```iter = iter(iterable)
target = iter.__next__()
while target:
sub-statement
sub-statement
...
target = iter.__next__()
else:
sub-statement
sub-statement
...
```

Two special statements can be used the sub-statement block:

• "break" statement can be used to break the "for" statement and terminate its execution.
• "continue" statement can be used to skip the remainder of the sub-statement block and jump back to the "for" clause header.

Here is a Python sample code, for_test.py, that shows you how to use "for" statements.

```#  for_test.py
#
upperLimit = 20
for i in range(3, upperLimit):
isPrime = True
for j in range(2, 1+i//2):
isPrime = i%j > 0
if not isPrime:
break

if isPrime:
print("   "+str(i)+" is a prime number.")

print("Reached the upper limit "+str(upperLimit))
```

If you run this sample code, you should get:

```herong\$ python for_test.py
3 is a prime number.
5 is a prime number.
7 is a prime number.
11 is a prime number.
13 is a prime number.
17 is a prime number.
19 is a prime number.
Reached the upper limit 20
```

Notice that the range() function returns a "range" object. But it implements the "iterable" interface, so it is considered as an "iterable" object.

You can use the iter(object) function to check if an object is "iterable" or not. For example:

```>>> iter(range(0,10))
<range_iterator object at 0x1095a1240>

>>> iter([9,1,1])
<list_iterator object at 0x109264160>

>>> iter((9,1,1))
<tuple_iterator object at 0x1095a18e0>

>>> iter('911')
<str_iterator object at 0x109264160>

>>> iter(911)
TypeError: 'int' object is not iterable
```