When
we have a list of things to loop through, we can construct a definite loop
using for statement. We call the while statement an indefinite loop because it
simply loops until some condition becomes False whereas the for loop is looping
through a known set of items so it runs through as many iterations as there are
items in the set.
The
syntax of a for loop is similar to the while loop in that there is a for
statement and a loop body:
movies =['Terminator 1','Terminator 2', 'Terminator 3' ] for movie in movies: print 'I watched:', movie print 'Done!'
In
Python the variable movies is a list of three strings and the for loop goes
through the list and executes the body once for each of the three strings in
the list resulting in this output:
I watched: Terminator 1 I watched: Terminator 2 I watched: Terminator 3 Done!
Translating
for loop to English: Run the statements in the body of the for loop once for
each movie in the set named movies
Looking
at the for loop, for and in are reserved Python keywords, and movie and movies
are variables.
for movie in movies: Print ‘I watched:’ , movie
Movie is
the iteration variable for the for loop. The variable movie changes for each
iteration of the loop and controls when the for loop completes. The iteration
variable steps successively through the three strings stored in movies variable.
Nema komentara:
Objavi komentar