For-loops
Now let's take a look at the other type of Python loop...
The for loop
Unlike the while loop, which executes any number of times until the stopping condition occurs, the for loop iterates over a sequence, visiting each element of the sequence in turn. Python's for loop is very general, and can repeat over any iterable sequence of items. It can iterate over the elements of a list, accessing each of the list elements in order. It can iterate over data in other container types, as described in later pages. It can iterate over a generator or other type of object that supports lazy evaluation, in which each element of a sequence is generated and returned as it is needed.
Here is the basic syntax of the for loop:
for value in iterable:
statement1
statement2
The following shows a simple example:
Using range()
Often we simply want a loop to repeat some integer number of times. The range()
function provides support for this by producing a sequence of integers within a specified interval or range, with an optional step size between successive integers (default step=1). In its simplest form, range()
takes a single integer argument N and produces all integers starting at 0 and stopping at one less than N (such that N integers are produced in all).
In Python 3, range()
supports lazy evaluation such that each integer in the sequence is produced one at a time (i.e., each time through a for loop) without ever requiring the explicit construction of a list of integers. (In Python 2, the range()
function returns a list of integers, and the xrange()
function supports lazy evaluation.)
Additional arguments to the range
function may be used to specify more general sequences of integers. The function can take one, two, or three integer inputs:
- range(b): produce sequence of integers starting at 0 and ending at b-1
- range(a,b): produce sequence of integers starting at a and ending at b-1
- range(a,b,s): produce sequence of integers starting at a, incremented by s, and ending before reaching b; the increment s can be negative
Mini-exercise: for-loop with a nested if
Instead of a while-loop, we can use a for-loop to set a maximum number of tries when asking a user for input
- Write a for-loop that counts to 5
- In the loop, ask the user to enter an integer
- Test the type of the input to see if it is an integer [Hint: Use the same test as in the if/else and while-loop exercises]
- If the test succeeds, exit the loop and report to the user what integer they have entered.
- If the test does not succeed, tell the user, "That is not an integer"
- If the user does not manage to correctly enter an integer after 5 tries, tell the user, "You have not entered an integer. Bye!", and exit. (Hint: you might want to set a flag that indicates whether an integer was successfully entered.)
Question: Why doesn't the "if" need an "else" clause?