| Python | PHP |
函數調用 | abs() | abs() |
數據類型轉換 | int()、float()、str()、bool() | intval()、(int) |
可變函數 | a = abs print(a(-1)) | function test($a){ return abs($a); } $a = "test"; echo $a(-2); |
函數定義 | def test(x): if x>0: return x else: return -x print(test(-10)) |
|
return | 會結束整個函數體 直接寫return返回none |
|
空函數
pass可以作爲佔位符使用,使空函數不報錯正常執行 | def nop(): pass |
|
數據類型檢查 | isinstance(object, classinfo) classinfo (tuple,dict,list,int,float等) | is_int() |
多元素返回 實際返回一個元組tuple,省略括號 | def test(): return a,b 接收x,y = test() 按tuple的順序接收 |
|
| Python | PHP |
函數參數 | 位置參數外,還可以使用默認參數、可變參數和關鍵字參數 | 位置參數、默認參數 |
位置參數 (必須) | def test(x): return x*x | function test(x){ return x*x; } |
默認參數 (默認值)
當不按順序提供部分默認參數時,需要把順序改變的參數名寫上。 test(n=3,x=3)
默認參數必須指向不變對象,例如None | def test(x,n=2): sum = 1 while n>0: sum = sum * x n = n - 1 return sum | function test(x=2){ return x*x; } |
可變參數 不確定參數個數時使用 自動組裝成tuple | def allow_change(*numbers): sum = 0 for i in numbers: sum = sum + i*i return sum print(allow_change(1,2,3))
如果參數是一個list或tuple list = [1,2,3] print(allow_change(*list)) |
|
關鍵字參數 0個或任意個含參數名的參數 自動組裝成dict | def keyword(**kw): return kw print(keyword(name= "tony"))
如果參數是一個dict dict = [1,2,3] print(keyword(**dict)) 函數內部的操作不會影響到外部 |
|
命名關鍵字參數 (限制關鍵字參數) 必須寫參數名 可以含默認參數 | def limit(name, *,age): return name,age print(limit("mary",age=18)) *號後面的爲限制輸入命名參數 可變參數後面接命名關鍵字參數可以不用再寫一次*號 輸入其他變量的時候就會報錯 |
|
| Python | PHP |
遞歸 | def fact(n): if n==1: return 1 return n * fact(n - 1) print(fact(4)) |
|
尾遞歸 | def fact(n): return fact_iter(n, 1)
def fact_iter(num, product): if num == 1: return product return fact_iter(num - 1, num * product)
|
|
漢諾塔 | def move(n,a,b,c): if n==1: print(a, '-->', c) else: move(n - 1, a, c, b) move(1, a, b, c) move(n - 1, b, a, c)
print(move(3, 'A', 'B', 'C'))
如果A上面只有一個,直接放到C上,如果不止一個,先把一個上面的全放到B,然後把一個放到C,然後把B上的放到C |
|