主要內容
1.函數基本語法及特性
2.參數與局部變
3.返回值 4.遞歸
5.名函數 6.函數式編程介紹
7.階函數 8.內置函數
函數基本語法及特性
定義
數學函數定義:一般的,在一個變化過程中,如果有兩個變量x和y,并且對于x的每一 個確定的值,y都有唯一確定的值與其對應,那么我們就把x稱為自變量,把y稱為因變 量,y是x的函數。自變量x的取值范圍叫做這個函數的定義域。
但編程中的「函數」概念,與數學中的函數是有很 同的 函數是邏輯結構化和過程化的一種編程方法
函數的優點
減少重復代碼
使程序變的可擴展
使程序變得易維護
函數與過程
定義函數
def fun1(): #函數名稱
"The function decription" print("in the func1") return 0 #返回值
定義過程
def fun2():"The progress decription"print("in the func2")函數與過程 過程就是沒有返回值的函數 但是在python中,過程會隱式默認返回none,所以在python中即便是過程也可以算作函數。
def fun1():  "The function decription"  print("in the func1")  return 0def fun2():  "The progress decription"  print("in the func2")x=fun1()y=fun2()print("from func1 return is %s" %x)print("from func2 return is %s" %y)結果為:
in the func1in the func2from func1 return is 0from func2 return is None
返回值
要想獲取函數的執 結果,就可以 return語 把結果返回。
函數在執 過程中只要遇到return語 ,就會停 執 并返回結果,所以也可以 解為 return 語 代表著函數的結束,如果未在函數中指定return,那這個函數的返回值為None。
接受返回值
賦予變量,例如:
def test():  print('in the test')  return 0x=test()返回什么樣的變量值
return 個數沒有固定,return的類型沒有固定。 例如:
def test1():  print('in the test1')def test2():  print('in the test2')  return 0def test3():  print('in the test3')  return 1,'hello',['alex','wupeiqi'],{'name':'alex'}def test4():  print('in the test4')  return test2x=test1()y=test2()z=test3()u=test4()print(x)print(y)print(z)print(u)結果是:
in the test1
in the test2
in the test3
in the test4
None
0
(1, 'hello', ['alex', 'wupeiqi'], {'name': 'alex'})
<function test2 at 0x102439488>
返回值數=0:返回None 沒有return
返回值數=1:返回object return一個值,python 基本所有的數據類型都是對象。
返回值數>1:返回tuple, return多個值。
返回可以返回函數:return test2會將test2的內存地址返回。
為什么要有返回值?            
新聞熱點
疑難解答