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
- six_sided()
- make_fair_dice(6)
- make_test_dice(6)
答案:1 注意返回值是不是函数,一定要随时都清楚变量是什么类型
for num in num_rolls:
报错:TypeError: ‘int’ object is not iterable
原因:num_rolls是int类型,不能直接用int进行迭代,而必须加个range。