A Python for loop can traverse any sequence of items, such as a list or a string.
Grammar:
The syntax format for the For loop is as follows:
For in sequence: statements(s)
#!/usr/bin/python#-*-Coding:utf-8-*-ForLetterInch ' Python ': # The first instance of print ' current letter: ' , letterfruits = [ ' banana ' Span class= "pun" >, ' Apple ' , ' Mango ' ]for fruit Span class= "KWD" >in Fruits: # second instance print ' current letter: ' Fruitprint "good bye!"
Iterating through the sequence index
Another way to perform a loop is through an index, as in the following example:
#!/usr/bin/python#-*-Coding:utf-8-*-fruits = [ ' banana ' Span class= "pun" >, ' Apple ' , ' Mango ' ]for index Span class= "KWD" >in Range (len ( fruits print current fruit: ' , Fruits[index]print "good bye!"
In the above example we used the built-in function Len () and range (), and the function Len () returns the length of the list, that is, the number of elements. Range returns the number of a sequence.
Looping with Else statements
In Python, for ... else means that the statement in for is no different from normal, while the statement in else is executed when the loop is executed normally (that is, for not breaking out by break), while ... else is the same.
The following example:
#!/usr/bin/python#-*-Coding:utf-8-*-ForNumInchRange(10,20): # Iterations of numbers between 10 and 20 ForIInchRange(2,Num): # based on factor iterations IfNum%I== 0: # Determine the first factor J=num/i # calculates the second factor print % (num ,i,j) break # jump out of current loop else: # loop else part print Num, ' is a prime number '
Python Exercise 24