这篇教程Python for 循环语句写得很实用,希望能帮到您。 Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。 语法: for循环的语法格式如下: for iterating_var in sequence: statements(s) 流程图:  实例: 实例 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当前水果 : mangoGood bye!
通过序列索引迭代另外一种执行循环的遍历方式是通过索引,如下实例: 实例 fruits = ['banana', 'apple', 'mango']for index in range(len(fruits)): print '当前水果 :', fruits[index] print "Good bye!" 以上实例输出结果: 当前水果 : banana当前水果 : apple当前水果 : mangoGood bye! 以上实例我们使用了内置函数 len() 和 range(),函数 len() 返回列表的长度,即元素的个数。range返回一个序列的数。
循环使用 else 语句在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。 实例 for num in range(10,20): for i in range(2,num): if num%i == 0: j=num/i print '%d 等于 %d * %d' % (num,i,j) break else: print num, '是一个质数' 以上实例输出结果: 10 等于 2 * 511 是一个质数12 等于 2 * 613 是一个质数14 等于 2 * 715 等于 3 * 516 等于 2 * 817 是一个质数18 等于 2 * 919 是一个质数 Python While 循环语句 Python 循环嵌套 |