#(1)這裏順帶說下pass
# pass 過 的意思,防止代碼報錯,就是個佔位的,
if True:
# 不容許代碼塊裏面的內容爲空,用pass佔位
pass
#(2)break (只能用在循環當中 終止當前循環)
# 打印1~10 若是遇到 5 終止循環
i = 1
while i <= 10:
if i == 5:
break
print(i)
i += 1
執行結果:
1
2
3
4
# 多循環 (break 終止當前循環)
i = 1
while i <= 3: # 外循環
j = 1
while j <= 3: #內循環
if j == 2:
print(i, j)
break #終止的是當前循環,即內循環,跳出當前循環後,繼續執行外循環
j += 1
i += 1
執行結果:
1 2
2 2
3 2
#(3)continue (跳過當前循環,從下一次循環開始)
# 打印1 ~ 5 跳過2
i = 1
while i <= 10:
if i == 5:
# continue 跳過當前循環 即下面的代碼不走了 直接回到循環條件的判斷裏了
i += 1
continue
print(i)
i += 1
執行結果:
1
3
4
5
#(4)1~100 打印全部不含有4的數字
# 第一種
i = 1
while i <= 100:
# 個位含有4的 或者 十位含有4的都不要 都跳過
if i % 10 == 4 or i // 10 == 4:
i += 1 # 注意 不加i+=1 會死循環
continue
print(i)
i += 1
# 第二種
print("<==11==>")
i = 1
while i <= 100:
res = str(i) # 強轉整型位字符串
if '4' in res: # 字符串'4'不在裏面
i += 1
continue
print(i)
i += 1