Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Python for loop statement


May 10, 2021 Python2


Table of contents


Python for loop statement

The Python for loop can traverse any sequence of items, such as a list or a string.

Grammar:

The syntax format for the loop is as follows:

for iterating_var in sequence: 
   statements(s)

Flow chart:

Python for loop statement

Instance:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

for letter in 'Python':     # 第一个实例
   print '当前字母 :', letter

fruits = ['banana', 'apple',  'mango']
for fruit in fruits:        # 第二个实例
   print '当前字母 :', fruit

print "Good bye!"
Try it out . . .


The above example output results:

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!

Iterates through the sequence index

Another way to traverse a loop is through an index, as follows:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
   print '当前水果 :', fruits[index]

print "Good bye!"

The above example output results:

当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!

In the above example we used the built-in functions len() and range(), which return the length of the list, i.e. the number of elements. Range returns the number of sequences.


The else statement is cycled

In Python, for ... E lse means that the statement in for is no different from the normal one, and that the statement in else executes when the loop is normally executed (i.e. for is not interrupted by a break jump), while ... The same is true of else.

Here's an example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

for num in range(10,20):  # 迭代 10 到 20 之间的数字
   for i in range(2,num): # 根据因子迭代
      if num%i == 0:      # 确定第一个因子
         j=num/i          # 计算第二个因子
         print '%d 等于 %d * %d' % (num,i,j)
         break            # 跳出当前循环
   else:                  # 循环的 else 部分
      print num, '是一个质数'

The above example output results:

10 等于 2 * 5
11 是一个质数
12 等于 2 * 6
13 是一个质数
14 等于 2 * 7
15 等于 3 * 5
16 等于 2 * 8
17 是一个质数
18 等于 2 * 9
19 是一个质数
Try it out . . .

More instances

Print 1-9 Triangle Array:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

for i in range(1,11):
    for k in range(1,i):
        print k,
    print "\n"

The above example output results:

1 

1 2 

1 2 3 

1 2 3 4 

1 2 3 4 5 

1 2 3 4 5 6 

1 2 3 4 5 6 7 

1 2 3 4 5 6 7 8 

1 2 3 4 5 6 7 8 9 

Print hollow iso-edge triangles:

#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 打印空心等边三角形 
rows = int(raw_input('输入行数:'))
for i in range(0, rows):
    for k in range(0, 2 * rows - 1):
        if (i != rows - 1) and (k == rows - i - 1 or k == rows + i - 1):
            print " * ",
        elif i == rows - 1:
            if k % 2 == 0:
                print " * ",
            else:
                print "   ",
        else:
            print "   ",
    print "\n"