函數:將某些共有的功能抽象出來,能夠直接調用,避免重複定義函數
1
1 def power(x, n = 2):#默認參數 2 2 s = 1 3 3 while n > 0: 4 4 n = n -1 5 5 s = s * x 6 6 return s
1 def enroll(name, gender, age = 6, city = 'beijing'):#多個默認參數 2 print('name:',name) 3 print('gender:',gender) 4 print('age:',age) 5 print('city:',city)
1 def fact(n):#遞歸函數,調用自身 2 if n==1: 3 return 1 4 else: 5 return n * fact(n-1)
1 def move(n, a, b, c):#漢諾塔遞歸 2 if n == 1: 3 print('move', a, '-->', c) 4 else: 5 move(n-1, a, c, b)# 不太理解爲何是n-1 6 move(1, a, b, c)# 不太理解爲何是1,爲何用move 7 move(n-1, b, a, c)