@2020.3.20 ...
@2020.3.20
1、函數對象優化多分支if的代碼練熟
def foo():
print('foo')
def bar():
print('bar')
dic={
'foo':foo,
'bar':bar,
}
while True:
choice=input('>>: ').strip()
if choice in dic:
dic[choice]()
2、編寫計數器功能,要求調用一次在原有的基礎上加一 溫馨提示: I:需要用到的知識點:閉包函數+nonlocal II:核心功能如下: def counter(): x+=1 return x 要求最終效果類似 print(couter()) # 1 print(couter()) # 2 print(couter()) # 3 print(couter()) # 4 print(couter()) # 5
def f1(): x=0 def counter(): nonlocal x x+=1 return x return counter counter=f1() print(counter()) print(counter()) print(counter()) print(counter()) print(counter())