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 Iterating_var in sequence: statements (s)
Flow chart:
Instance:
#!/usr/bin/python#-*-coding:utf-8-*-for letters in ' Python ': # First Instance of print ' Current letter: ', letterfruits = [' Banana ', ' Apple ', ' mango ']for fruit in fruits: # The second instance of print ' Current letter: ', fruitprint ' good bye! '
The result of the above example output:
Current Letter: P Current Letter: y current letter: T current letter: H current Letter: o Current letter: N Current letter: Banana Current Letter: Apple Current letter: Mangogood 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 ', ' apple ', ' Mango ']for index in range (len (fruits)): print ' when Former fruit: ', fruits[index]print ' good bye! '
The result of the above example output:
Current fruit: Banana current fruit: Apple current fruit: Mangogood 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-*-for num in range (10,20): # iterations between 10 and 20 for the number for I in range (2,num): # based on factor iteration
if num%i = = 0: # Determine the first factor j=num/i # Calculates the second factor print '%d equals%d *%d '% (num,i,j) Break # jumps out of the current loop
else: # The else part of the Loop print num, ' is a prime number '
The result of the above example output:
10 equals 2 * 511 is a prime number 12 equals 2 * 613 is a prime number 14 equals 2 * 715 equals 3 * 516 equals 2 * 817 is a prime number 18 equals 2 * 919 is a prime number