python for

By: Ashley J Viewed: 177 times  Printer Friendly Format    


Python for statement repeats execution of a statement, or block of statements, controlled by an iterable expression. Here’s the syntax of the for statement:

for target in iterable:
    statement(s)
   

The in keyword is part of the syntax of the for statement; its purpose here is distinct from the in operator, which tests membership. iterable may be any Python expression suitable as an argument to built-in function iter, which returns an iterator object (explained in detail in the next section). In particular, any sequence is iterable. target is normally an identifier that names the control variable of the loop; the for statement successively rebinds this variable to each item of the iterator, in order. The statement or statements that make up the loop body execute once for each item in iterable (unless the loop ends because of an exception or a break or return statement).

Here’s a typical for statement:

for letter in 'ciao':
    print('give me a', letter, '...')

This prints out as follows:

give me a c ...
give me a i ...
give me a a ...
give me a o ...

A for statement can also include an else clause, and break and continue statements. 



Most Viewed Articles (in Python )

Latest Articles (in Python)

Comment on this tutorial