5.1 while循環
- 說明:關鍵字 while ,判斷條件爲真就一直執行
- 例子:
1: name = '' 2: while not name.strip(): 3: name = input("Please input your name:") 4: print("Hello,", name)
5.2 for循環
- 說明:能夠用於迭代集合中的每一個元素;
- 例子:
1: #遍歷列表中的各個元素 2: >>> x = [1,2,3,4,5] 3: >>> for number in x: 4: print (number) 5: 1 6: 2 7: 3 8: 4 9: 5 10: >>> 11: 12: #使用內建函數range 13: >>> x = range(10) 14: >>> x 15: range(0, 10) 16: >>> for number in x: 17: print(number) 18: 0 19: 1 20: 2 21: 3 22: 4 23: 5 24: 6 25: 7 26: 8 27: 9 28: >>> 29:
5.3 循環遍歷字典元素
- 說明:經過keys遍歷字典,或者經過values;
- 例子:
1: x = {'a':'1', 'b':'2', 'c':'3'} 2: for key in x.keys(): 3: print (key, x[key]) 4: 5: for val in x.values(): 6: print(val) 7:
5.4 一些迭代工具
5.4.1 並行迭代
- 說明:zip內置函數能夠將多個序列「壓縮」成一個元組的序列;
- 例子:
1: >>> x = list(range(0,5)) 2: >>> y = list(range(5,10)) 3: >>> z = list(range(10, 15)) 4: >>> z 5: [10, 11, 12, 13, 14] 6: >>> y 7: [5, 6, 7, 8, 9] 8: >>> x 9: [0, 1, 2, 3, 4] 10: 11: >>> zipped = zip(x, y, z) 12: >>> list(zipped) 13: [(0, 5, 10), (1, 6, 11), (2, 7, 12), (3, 8, 13), (4, 9, 14)] 14: >>> 15:
5.4.2 編號迭代
- 說明:使用內建函數enumerate來進行迭代操做;
- 例子:
1: >>> mylist = ['12312', '12ab', '123sa', '1231s'] 2: >>> for index, string in enumerate(mylist): 3: print(index, string) 4: 5: 6: 0 12312 7: 1 12ab 8: 2 123sa 9: 3 1231s 10: >>> 11:
5.4.3 翻轉和排序迭代
- 說明:內建函數reversed用於翻轉序列,內建函數sorted用於對序列排 序,他們都是返回操做後的序列,不對原序列進行修改;
- 例子:
1: >>> data = [1,67,1,13,14,61,2] 2: >>> sorted(data) 3: [1, 1, 2, 13, 14, 61, 67] 4: >>> list(reversed(data)) 5: [2, 61, 14, 13, 1, 67, 1] 6: >>> 7:
5.5 跳出循環
5.5.1 break
- 說明:符合條件時直接中斷循環;
- 例子:
1: >>> import math 2: >>>for x in range(99, 0, -1): 3: >>> root = math.sqrt(x) 4: >>> if root == int(root): 5: >>> print ('Max number is:', x) 6: >>> break 7: 8: Max number is 81 9:
5.5.2 continue
- 說明:結束當前循環,並跳到下一輪循環開始;
- 例子:
1: #一個打印偶數的例子,不加else 語句,程序也能正確執行 2: >>> for x in range(10): 3: if x%2 == 0: 4: print(x) 5: else: 6: continue 7: 8: 9: 0 10: 2 11: 4 12: 6 13: 8 14: >>> 15:
5.5.3 while True/break
- 說明:while True部分實現了一個永不中止的循環,由內部的if判斷語 句控制跳出循環;
- 例子:
1: while True: 2: word = input("Please enter a word:") 3: if not word: 4: break 5: print("You input:" , word) 6: 7: Please enter a word:TEst 8: You input: TEst 9: Please enter a word:ls 10: You input: ls 11: Please enter a word: 12: >>> 13:
5.5.4 循環中的else子句
- 說明:else子句能夠用於判斷循環操做是否始終沒有執行break操做。
- 例子:
1: #設置一個奇數序列,判斷裏面是否是有偶數(一個蛋疼的程序,哈哈) 2: x = list(range(1,100,2)) 3: for val in x: 4: if val%2 == 0: 5: print (x) 6: break; 7: else: 8: print("Did not break!") 9: #執行結果 10: Did not break! 11: