python for 循环

kuaidi.ping-jia.net  作者:佚名   更新日期:2024-08-01
python for 循环是怎样的呢?下面就让我们一起来了解一下吧:
for是属于python下的循环语句,它能够遍历任何序列的项目,比如一个列表或是一个字符串。
for循环的语法格式为:
for iterating_var in sequence:
statements(s)
说明:
在python中,for经常会与else一起出现,for中的语句其实与普通的没有区别,而else中的语句会在循环正常执行完的情况下执行,也就是说for并不是通过break跳出而中断的。
参考范例:
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!
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!