CS61A HOG

CS61A project hog

以後記得每天git push ^^(git使用:參考)

知識1:global 和 nonlocal比較?
global改變全局變量
nonlocal嵌套函數時,改變上一層變量的值,如果上一層找不到同名的變量會報錯
知識2:python交換兩個元素
a,b = b,a


問題1:爲何函數執行多遍,都是執行裏面的嵌套函數?
找到了答案:因爲返回值return的就是那個嵌套函數啊

問題2:爲何要函數裏嵌套一個函數用呢?
答:這叫做閉包,是函數式編程常用的技巧。(面向函數和麪向對象都算函數式編程)
比如一個求和函數,並不想立刻求和,返回一個求和函數f,再次調用f()時才求和

注意
1.一個函數返回一個函數f後,內部的局部變量還可以被f用
2.重點返回閉包時牢記一點:返回函數不要引用任何循環變量,或者後續會發生變化的變量。

問題3:不理解函數何時調用腫麼辦???
重點:遇到f()這樣的就是調用一次

問題4:python自己return自己 難道不會死循環嗎?
不會啊,返回值是個函數,並不是調用函數,一定要注意何時調用!調用


def make_test_dice(*outcomes):
index = len(outcomes) - 1
print(“make_test_dice”,index,id(index))
def dice():
nonlocal index
index = (index + 1) % len(outcomes)
print(“dice”,index,id(index))
return outcomes[index]
return dice
test_dice = make_test_dice(4,2,1)
print(test_dice())
print(test_dice())
print(test_dice())
print(type(test_dice))
print(type(make_test_dice))
print(type(make_test_dice(4,2,1)))
print(test_dice is make_test_dice(4,2,1))

以下哪一個正確
Choose the number of the correct choice:
0) six_sided

  1. six_sided()
  2. make_fair_dice(6)
  3. make_test_dice(6)
    答案:1 注意返回值是不是函數,一定要隨時都清楚變量是什麼類型

for num in num_rolls:
報錯:TypeError: ‘int’ object is not iterable
原因:num_rolls是int類型,不能直接用int進行迭代,而必須加個range。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章