循环控制语句可以更改语句执行的顺序。Python支持以下循环控制语句:
控制语句 描述 break 语句 在语句块执行过程中终止循环,并且跳出整个循环 continue 语句 在语句块执行过程中终止当前循环,跳出该次循环,执行下一次循环。 pass 语句 pass是空语句,是为了保持程序结构的完整性。
#!/usr/bin/python count = 0 while (count < 9): print 'The count is:', count count = count + 1 print "Good bye!"
循环使用 else 语句 在 python 中,while … else 在循环条件为 false 时执行 else 语句块:
#!/usr/bin/python count = 0 while count < 5: print count, " is less than 5" count = count + 1 else: print count, " is not less than 5"
可以遍历任何序列的项目,如一个列表或者一个字符串
#!/usr/bin/python # -*- coding: UTF-8 -*- for letter in 'Python': # 第一个实例 print '当前字母 :', letter fruits = ['banana', 'apple', 'mango'] for fruit in fruits: # 第二个实例 print '当前水果 :', fruit print "Good bye!"
通过序列索引迭代 另外一种执行循环的遍历方式是通过索引,如下实例:
#!/usr/bin/python # -*- coding: UTF-8 -*- fruits = ['banana', 'apple', 'mango'] for index in range(len(fruits)): print '当前水果 :', fruits[index] 循环使用 else 语句 在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。
for num in range(10,20): # 迭代 10 到 20 之间的数字 for i in range(2,num): # 根据因子迭代 if num%i == 0: # 确定第一个因子 j=num/i # 计算第二个因子 print '%d 等于 %d * %d' % (num,i,j) break # 跳出当前循环 else: # 循环的 else 部分 print num, '是一个质数'
