day6 break continue for
阿新 • • 發佈:2017-11-14
es2017 pri lan += [1] for col .py wid
1.for
In [1]: name = "lanwang" In [2]: for temp in name: ...: print("----") ...: print(temp) ...: ---- l ---- a ---- n---- w ---- a ---- n ---- g
2.break (整個while循環全部結束)
1)打印1-100的偶數.py
i = 1 while i <= 5: print("-----") if i == 3: break print(i) i += 1 #運行結果 ----- 1 ----- 2 -----
2)打印1-100的20個偶數.py
i = 1 count = 0 while i <= 100: #if i 是偶數打印 if i%2 == 0: print(i) count +=1 if count == 20 : break i += 1
3)while嵌套中的break (就近原則)
3.continue
錯誤用法:
i = 1 while i <= 5: print("-----") if i == 3: # break continue #一次循環不執行 print(i) i += 1 print("=======") #執行結果 -----
1 -----
2 ----- ----- #當i=3 時,永遠跳出本次循環,下面的2行語句未能執行,一直重復 ----- ----- ----- ----- ----- ----- -----
正確用法:
i = 1 while i <= 5: i+= 1 #i+=1 放到前面??? print("-----") if i == 3: #break continue #結束一次循環, 轉而下一次的循環 print(i) print("=======") #運行結果 ----- 2 ----- ----- 4 ----- 5 ----- 6 =======
day6 break continue for