6.1
- range 函數用來創建一個數字列表,它的范圍是從起始數字開始到結束數字之前
1 >>> for x in range(0,5): 2 print('Hello %s' % x) 3 4 Hello 0 5 Hello 1 6 Hello 2 7 Hello 3 8 Hello 4
?
-
1 >>> print(list(range(10,20))) 2 [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
range函數并不是真的創建了一個數字的列表,它返回的是一個“迭代器”。
- 不用非得在for 循環中使用range或者List函數,你也可以使用一個創建好的列表。
1 >>> wizard_list = ['a','b','c','d','e'] 2 >>> for i in wizard_list: 3 print(i) 4 5 a 6 b 7 c 8 d 9 e
? 這段代碼意思是對于 wizard_list中每個元素,把它的值放到變量i里,然后打印出這個變量的內容。
- 更復雜的for循環
1 >>> hugehairypants = ['huge','hairy','pants'] 2 >>> for i in hugehairypants: 3 print(i) 4 for j in hugehairypants: 5 print(j) 6 7 8 huge 9 huge 10 hairy 11 pants 12 hairy 13 huge 14 hairy 15 pants 16 pants 17 huge 18 hairy 19 pants
?
?
6.2 while循環
- for循環是針對指定長度的循環,而while循環是針對用于你事先不知道何時停止的循環
- 作業
1 >>> for x in range(0,20): 2 print('hello %s' % x) 3 if x < 9: 4 break 5 6 7 hello 0
?
1 >>> age =0 2 >>> while age<23: 3 print(age) 4 age = age+2
?