Exercise 32python
代碼app
the_count = [1, 2, 3, 4, 5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] # this first kind of for-loop goes through a list for number in the_count: print "This is count %d" % number # same as above for fruit in fruits: print "A fruit of type: %s" % fruit # also we can go through mixed lists too # notice we have to use %r since we don't know what's in it for i in change: print "I got %r" % i # we can also build lists, first start with an empty one elements = [] # then use the range function to do 0 to 5 counts for i in range(0,6): print "Adding %d to the list." % i # append is a function that lists understand elements.append(i) # now we can print them out too for i in elements: print "Element was: %d" % i
輸出函數
Notes:oop
①range(start,end)返回一個整型序列,範圍是start至end-1ui
>>> range(0.6) [0, 1, 2, 3, 4, 5]
②for...in...迭代循環適用於字符串、列表等序列類型this
③序列之間能夠用加號相連,組成新序列code
>>> elements = [] >>> elements + range(0,6) [0, 1, 2, 3, 4, 5]
Exercise 33
ci
代碼element
i = 0 numbers = [] while i < 6: print "At the top i is %d" % i numbers.append(i) i = i + 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers:" for num in numbers: print num
輸出字符串
Notes:
①while經過檢查布爾表達式的真假來肯定循環是否繼續。除非必要,儘可能少用while-loop,大部分狀況下for-loop是更好的選擇;使用while-loop時注意檢查布爾表達式的變化狀況,確保其最終會變成False,除非你想要的就是無限循環
②加分習題一代碼改寫
代碼
i = 0 numbers = [] def numbers_list(x): global numbers, i while i < x: print "At the top i is %d" % i numbers.append(i) i = i + 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i numbers_list(7) print "The numbers:" for num in numbers: print num
輸出
PS:函數需注意局部變量和全局變量的問題。
③加分習題二代碼改寫
代碼
i = 0 numbers = [] def numbers_list(x, y): global numbers, i while i < x: print "At the top i is %d" % i numbers.append(i) i = i + y print "Numbers now: ", numbers print "At the bottom i is %d" % i numbers_list(7, 3) print "The numbers:" for num in numbers: print num
輸出
Exercise 34
本節無代碼,主要練習列表的切片、序數與基數問題
練習:
The animal at 1 is the 2nd animal and is a python. The 3rd animal is at 2 and is a peocock. The 1st animal is at 0 and is a bear. The animal at 3 is the 4th animal and is a kanaroo. The 5th animal is at 4 and is a whale. The animal at 2 is the 3rd animal and is a peocock. The 6th animal is at 5 and is a platypus. The animal at 4 is the 5th and is a whale.