1 例如1: 2 代码: 3 效果循环猜guess_age,猜对了结束循环,猜错了,无限循环 4 guess_age=56 5 count=0 6 while True: 7 yang_age=int(input(‘age:‘)) 8 if yang_age==int(guess_age): 9 print(‘bingo‘) 10 break 11 elif yang_age < guess_age: 12 print(‘guess smaller‘) 13 else: 14 print(‘guess big‘) 15 代码执行结果: 16 age:20 17 guess smaller 18 age:56 19 bingo 20 21 例如2: 22 代码如下: 23 效果如下: count计数,猜年龄猜错的次数不能操作三次。 24 guess_age=56 25 count=0 26 while count<3: 27 yang_age=int(input(‘age:‘)) 28 29 if yang_age==int(guess_age): 30 print(‘bingo‘) 31 break 32 elif yang_age < guess_age: 33 print(‘guess smaller‘) 34 else: 35 print(‘guess big‘) 36 count = count + 1 37 else: 38 print(‘you have tried too many times..fuck off‘) 39 40 41 代码执行结果: 42 age:13 43 guess smaller 44 age:123 45 guess big 46 age:4 47 guess smaller 48 you have tried too many times..fuck off 49 50 例如3: 51 代码: 52 效果:如果猜了三次count=3,会再次询问你要不要继续猜,如果继续,count清0,重新回到while循环。 53 guess_age=56 54 count=0 55 while count<3: 56 yang_age=int(input(‘age:‘)) 57 58 if yang_age==int(guess_age): 59 print(‘bingo‘) 60 break 61 elif yang_age < guess_age: 62 print(‘guess smaller‘) 63 else: 64 print(‘guess big‘) 65 count = count + 1 66 if count==3: 67 countinue_confirm=input(‘do you want to keep guessing:‘) 68 if countinue_confirm !=‘n‘: 69 count=0 70 71 代码执行结果如下: 72 age:1 73 guess smaller 74 age:2 75 guess smaller 76 age:3 77 guess smaller 78 do you want to keep guessing:56 79 age:1 80 guess smaller 81 age:3 82 guess smaller 83 age:56 84 bingo 85 86 87 例如4: 88 代码如下: 89 效果:打印0-9的数字 90 for i in range(0,10): 91 print(‘loop‘,i) 92 代码执行结果如下: 93 loop 0 94 loop 1 95 loop 2 96 loop 3 97 loop 4 98 loop 5 99 loop 6 100 loop 7 101 loop 8 102 loop 9 103 104 优化: 105 效果:0-10打印偶数不打印奇数,步长为2 106 for i in range(0,10,2) 107 print(‘loop‘,i) 108 执行代码结果如下: 109 loop 0 110 loop 2 111 loop 4 112 loop 6 113 loop 8 114 115 116 例如5: 117 代码: 118 效果:打印10次j,而j的条件判断在【0-6】之间,当j=6时断开又重新循环到i,以此重复10次。 119 for i in range(10): 120 print(‘-----‘,i) 121 for j in range(10): 122 print(j) 123 if j>5: 124 break 125 代码执行结果如下: 126 ----- 0 127 0 128 1 129 2 130 3 131 4 132 5 133 6 134 ----- 1 135 0 136 1 137 2 138 3 139 4 140 5 141 6 142 ----- 2 143 0 144 1 145 2 146 3 147 4 148 5 149 6 150 ----- 3 151 0 152 1 153 2 154 3 155 4 156 5 157 6 158 ----- 4 159 0 160 1 161 2 162 3 163 4 164 5 165 6 166 ----- 5 167 0 168 1 169 2 170 3 171 4 172 5 173 6 174 ----- 6 175 0 176 1 177 2 178 3 179 4 180 5 181 6 182 ----- 7 183 0 184 1 185 2 186 3 187 4 188 5 189 6 190 ----- 8 191 0 192 1 193 2 194 3 195 4 196 5 197 6 198 ----- 9 199 0 200 1 201 2 202 3 203 4 204 5 205 6