目錄python
遍歷某個結構造成的循環運行方式函數
for <循環變量> in <遍歷結構>: <語句塊>
for
和in
組成,完整遍歷全部元素後結束fro i in range(N): <語句塊>
range()
函數產生的數字序列,產生循環for i in range(5): print(i)
0 1 2 3 4
for i in range(5): print('hello:', i)
hello: 0 hello: 1 hello: 2 hello: 3 hello: 4
fro i in range(M,N,K): <語句塊>
range()
函數產生的數字序列,產生循環for i in range(1, 6): print(i)
1 2 3 4 5
for i in range(1, 6, 2): print('hello:', i)
hello: 1 hello: 3 hello: 5
for c in s: <語句塊>
for c in 'python': print(c, end=',')
p,y,t,h,o,n,
for item in ls: <語句塊>
for item in [123, "PY", 456]: print(item, end=",")
123,PY,456,
for line in fi: <語句塊>
# fi.txt 優美勝於醜陋 明瞭勝於隱晦 簡潔勝於複雜
for line in fi: print(line)
優美勝於醜陋 明瞭勝於隱晦 簡潔勝於複雜
由條件控制的循環運行方式code
a = 3 while a > 0: a = a - 1 print(a)
2 1 0
# 死循環, (CTRL + C 退出執行) a = 3 while a > 0: a = a + 1 print(a)
for c in "PYTHON": if c == 'T': continue print(c, end=',')
P,Y,H,O,N,
for c in "PYTHON": if c == 'T': break print(c, end=',')
P,Y,
s = "PYTHON" while s != "": for c in s: print(c, end=',') s = s[:-1]
P,Y,T,H,O,N,P,Y,T,H,O,P,Y,T,H,P,Y,T,P,Y,P,
s = "PYTHON" while s != "": for c in s: if c == 'T': break print(c, end=',') s = s[:-1]
P,Y,P,Y,P,Y,P,Y,P,Y,P,
循環與elseblog
for <變量> in <遍歷結構>: <語句塊1> else: <語句塊2>
while <條件>: <語句塊1> else: <語句塊2>
for c in "PYTHON": if c == "T": continue print(c, end="") else: print("正常退出")
PYHON正常退出
for c in "PYTHON": if c == "T": break print(c, end="") else: print("正常退出")
PY
for…in
遍歷循環:計數、字符串、列表、文件…while
無限循環continue
和break
保留字:退出當前循環層次break
有關