Python for loop statement
Python for loop can iterate over any sequence of items, such as a list or a string.
Grammar:
The syntax format of the for loop is as follows:
statements(s)
Flow chart:
Example:
# -*- coding: UTF-8 -*-
for letter in 'Python': # First example
print 'Current letter:', letter
fruits = [ 'banana', 'apple', 'mango']
for fruit in fruits: # Second example
print 'Current letter:', fruit
print "Good bye! "
Try it»
The above example output result:
Current Letter: y
Current letter: t
Current letter: h
Current letter: o
Current letter: n
Current letter: banana
Current letter: apple
Current letter : mango
Good bye!
Iterate through sequence index
Another way to traverse a loop is through index, as shown in the following example:
# -*- coding: UTF-8 -*-
fruits = ['banana', 'apple', 'mango' ]
for index in range(len(fruits)):
print 'Current fruits:', fruits[index]
print "Good bye!"
The output result of the above example:
Current fruit: apple
Current fruit: mango
Good bye!
We used the built-in functions len() and range() in the above example. The function len() returns the length of the list, that is, the number of elements. range returns a sequence of numbers.
Looping using else statements
In python, for...else means this. The statements in for are no different from ordinary ones, and the statements in else will be in It is executed when the loop is executed normally (that is, for is not interrupted by break), and the same is true for while...else.
The following example:
# -*- coding: UTF-8 -*-
for num in range(10,20): # Iterate over numbers between 10 and 20
for i in range(2,num): # Iterate based on factors
if num%i == 0: #Determine the first factor
j=num/i #Calculate the second factor
print '%d equals %d * %d' % (num,i,j)
Break out of the current loop
else: # The else part of the loop
print num, 'is a prime number'
The above example output result:
11 is a prime number
12 is equal to 2 * 6
13 is a prime number
14 is equal to 2 * 7
15 is equal to 3 * 5
16 is equal to 2 * 8
17 is a prime number
18 is equal to 2 * 9
19 is a prime number
Try it»