1.概念解释:
for循环可以遍历任何序列的项目,如一个列表或者一个字符串,或者序列索引,或数值范围。程序框图如下:
2.代码演示:
A.遍历字符串及列表:
for letter in 'Python': # 第一个实例
print '当前字母 :', letter
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # 第二个实例
print '当前水果 :', fruit
print "Good bye!"
运行结果:
当前字母 : P
当前字母 : y
当前字母 : t
当前字母 : h
当前字母 : o
当前字母 : n
当前字母 : banana
当前字母 : apple
当前字母 : mango
Good bye!
B.通过序列索引迭代
#!/usr/bin/python
# -*- coding: UTF-8 -*-
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print '当前水果 :', fruits[index]
print "Good bye!"
运行结果:
当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!
C.数值范围内的迭代
for i in range(1,10):
print(i)
运行结果:
1
2
3
4
5
6
7
8
9