Python-for循环语句
Python中有很多序列形态的数据结构(如列表或字符串等),可以使用for循环进行遍历。
语法:
for循环的语法格式如下:
for iterating_var in sequence:
statements(s)
代码实例(代码可以在在线python3环境中运行)
for letter in 'ShowMeAI': # 第一个实例
print("当前字母: %s" % letter)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # 第二个实例
print('当前水果: %s'% fruit)
print("完成!")
以上代码输出结果:
当前字母: S
当前字母: h
当前字母: o
当前字母: w
当前字母: M
当前字母: e
当前字母: A
当前字母: I
当前水果: banana
当前水果: apple
当前水果: mango
完成!
通过序列索引迭代
另外一种执行循环的遍历方式是通过索引,如下实例(代码可以在在线python3环境中运行):
fruits = ['香蕉', '苹果', '葡萄']
for index in range(len(fruits)):
print('当前水果 : %s' % fruits[index])
print("完成!")
以上代码输出结果:
当前水果 : 香蕉
当前水果 : 苹果
当前水果 : 葡萄
完成!
以上实例我们使用了内置函数 len() 和 range(),函数 len() 返回列表的长度,即元素的个数。 range返回一个序列的数。