循环10次
1 #! /usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 for i in range(10): 5 print("loop:", i)
输出:
1 loop: 0 2 loop: 1 3 loop: 2 4 loop: 3 5 loop: 4 6 loop: 5 7 loop: 6 8 loop: 7 9 loop: 8 10 loop: 9
循环中用到continue,break两种方式跳出循环。
continue: 跳出本次循环,进行下次循环
1 for i in range(10): 2 if i<5: 3 continue 4 print("loop:", i )
break :跳出整个循环
1 for i in range(10): 2 if i>5: 3 break 4 print("loop:", i )
嵌套循环
1 for i in range(10): 2 print(‘---------‘, i) 3 for j in range(10): 4 print(j) 5 if j > 5: 6 break
输出:
1 --------- 0 2 0 3 1 4 2 5 3 6 4 7 5 8 6 9 --------- 1 10 0 11 1 12 2 13 3 14 4 15 5 16 6 17 --------- 2 18 0 19 1 20 2 21 3 22 4 23 5 24 6 25 --------- 3 26 0 27 1 28 2 29 3 30 4 31 5 32 6 33 --------- 4 34 0 35 1 36 2 37 3 38 4 39 5 40 6 41 --------- 5 42 0 43 1 44 2 45 3 46 4 47 5 48 6 49 --------- 6 50 0 51 1 52 2 53 3 54 4 55 5 56 6 57 --------- 7 58 0 59 1 60 2 61 3 62 4 63 5 64 6 65 --------- 8 66 0 67 1 68 2 69 3 70 4 71 5 72 6 73 --------- 9 74 0 75 1 76 2 77 3 78 4 79 5 80 6