首页 > IT科技 > python里的for循环

python里的for循环

   来源:人文屋    阅读: 1.06W 次
字号:

用手机扫描二维码 在手机上继续观看

手机查看

for是属于python下的循环语句,它能够遍历任何序列的项目,比如一个列表或是一个字符串。

for循环的语法格式为:

for iterating_var in sequence:

   statements(s)

说明:在python中,for经常会与else一起出现,for中的语句其实与普通的没有区别,而else中的语句会在循环正常执行完的情况下执行,也就是说for并不是通过break跳出而中断的。

python里的for循环

参考范例:

1、

输入代码:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

for letter in 'Python':     # 第一个实例

   print("当前字母: %s" % letter)

fruits = ['banana', 'apple',  'mango']

for fruit in fruits:        # 第二个实例

   print ('当前水果: %s'% fruit)

print ("Good bye!")

输出结果:

当前字母: P

当前字母: y

当前字母: t

当前字母: h

当前字母: o

当前字母: n

当前水果: banana

当前水果: apple

当前水果: mango

Good bye!

python里的for循环 第2张

2、

当然也可以通过序列索引迭代,具体代码如下:

#!/usr/bin/python

# -*- coding: UTF-8 -*-

fruits = ['banana', 'apple',  'mango']

for index in range(len(fruits)):

   print ('当前水果 : %s' % fruits[index])

print ("Good bye!")

输出结果:

当前水果 : banana

当前水果 : apple

当前水果 : mango

Good bye!

学习教育
IT科技
财经金融
旅游出行
生活妙招
美食美味
健康养生
体育健身