Python--function,python

來源:互聯網
上載者:User

Python--function,python

函數就是"變數".定義一個函數就是相當於將一個函數體賦值給函數名.

一、參數的調用

def test0(x,y,z):            #定義函數test0,形參x,y,z
  print("x=%d,y=%d,z=%d" %(x,y,z))  #依次輸出形參的值
test0(1,2,3)              #位置參數調用
test0(x=2,z=0,y=1)           #關鍵字調用
test0(2,z=1,y=3)            #位置參數與關鍵字調用,位置參數要在前

-----------------------------------------------------------------------------
x=1,y=2,z=3
x=2,y=1,z=0
x=2,y=3,z=1
=============================================================================
def test1(x,y=2):           #定義預設參數,可省略傳遞
  print("x=%d,y=%d" %(x,y))

test1(1)
-----------------------------------------------------------------------------
x=1,y=2
=============================================================================

def test2(*args):     #不固定形參,可傳遞多個,把關鍵字參數轉換成元組tuple
  print(args)
test2(1,2,3)
test2(*[1,2,3])
-----------------------------------------------------------------------------
(1, 2, 3)
(1, 2, 3)
=============================================================================
def test3(**kwargs):     #將字典作為形參,可傳遞多個,傳遞的值為key:value
  print(kwargs)
  print(kwargs['name'])
  print(kwargs['age'])
  print(kwargs['sex'])
test3(name='xy',age=23,sex="N")
test3(**{'name':'xy','age':23,'sex':'N'})
-----------------------------------------------------------------------------
{'name': 'xy', 'age': 23, 'sex': 'N'}
xy
23
N
{'name': 'xy', 'age': 23, 'sex': 'N'}
xy
23
N
=============================================================================

def test4(name,**kwargs):          #位置參數和字典參數傳遞值
  print(name,kwargs)
test4('xy',age=23,sex='N')
-----------------------------------------------------------------------------
xy {'age': 23, 'sex': 'N'}
=============================================================================
def test5(name,age=18,**kwargs):    #傳遞位置參數,關鍵字參數,字典參數
  print(name,age,kwargs)
test5('xy',sex='N',hobby='belle',age=23) #匹配不到形參時,參數後移至**kwargs
-----------------------------------------------------------------------------
xy 23 {'sex': 'N', 'hobby': 'belle'}
=============================================================================
def test6(name,age,*args,**kwargs):      #定義多個類型形參,tuple,字典
  print(name,age,args,kwargs)
test6('xy',23,'python','perl',linux='shell',sql='mariadb',sex='N')

              #依次匹配形參,傳遞的位置形參要在關鍵字形參前面
-----------------------------------------------------------------------------
xy 23 ('python', 'perl') {'linux': 'shell', 'sql': 'mariadb', 'sex': 'N'}
=============================================================================

二、函數的傳回值return

  函數中return表示函數結束

  Python中的函數的傳回值可以是一個參數,也可以是多個參數以元組格式返回

def return_test():
print("line one")
print("line two")
return 'hello',['nice','to','meet','you'],666 #返回多個參數
print("line three")        #return後面不執行
print(return_test())          #列印函數傳回值
-----------------------------------------------------------------------------

line one
line two
('hello', ['nice','to','meet','you'],666)    #傳回值為元組tuple格式

=============================================================================

 三、匿名函數

匿名函數只能有一個運算式,不用寫return,傳回值就是該運算式的結果

函數沒有名字,不必擔心函數名衝突

calc = lambda x:x**3    #lambda表示匿名函數,冒號前面的x表示函數參數

print("calc is %s" %calc(3))

-----------------------------------------------------------------------------

calc is 27

=============================================================================

四、函數內的局部變數與全域變數

name = 'xy'    #name為全域變數
def test7(name):            #函數內name為局部變數
  print("before change",name)
  name = "architect"        #函數內更改變數的值,函數外不會改變
  print("after change",name)    #函數內列印局部變數name的值
test7(name)
print(name)
-----------------------------------------------------------------------------
before change xy
after change architect
xy            #函數外的值
=============================================================================
school = "ahxh edu"
def test8(name):            #全域變數不會被局部改變
  global school            #global,函數中申明全域變數,不建議更改
  school = 'xwxh edu'        #將全域變數重新賦值
  print(school)
test8(school)
print(school)
-----------------------------------------------------------------------------
xwxh edu               #函數內的值
xwxh edu                #此處全域變數已被在函數中更改
=============================================================================
names_list=['xy','jack','lucy']
def test9():      #當傳遞list,tuple,字典時傳遞的是地址,函數中可改變全域變數
  names_list[0] = 'architect'
  print("inside func",names_list)
test9()
print(names_list)
-----------------------------------------------------------------------------
inside func ['architect', 'jack', 'lucy']        #函數內的值
['architect', 'jack', 'lucy']              #函數外的值
=============================================================================
五、函數的遞迴
    遞迴約999次啟動程式保護關閉進程,遞迴必須有明確的結束條件
    進入深一層次遞迴演算法要減少,遞迴的效率不高,容易導致棧溢出
def calc(n):
  print(n)
  return calc(n+1)                  #無限遞迴
calc(0)
-----------------------------------------------------------------------------
996
Traceback (most recent call last):
File "遞迴.py", line 8, in <module>
calc(0)
File "遞迴.py", line 7, in calc
return calc(n+1)
File "遞迴.py", line 7, in calc
return calc(n+1)
File "遞迴.py", line 7, in calc
return calc(n+1)
[Previous line repeated 992 more times]
File "遞迴.py", line 6, in calc
print(n)
RecursionError: maximum recursion depth exceeded while calling a Python object
=============================================================================
def calc(n):
  print(n)
  if int(n/2) ==0:
    return n
  return calc(int(n/2)) #遞迴調用函數
calc(10)
-----------------------------------------------------------------------------
10
5
2
1
=============================================================================
六、高階函數

把一個函數名當做實參傳遞給另外一個函數

傳回值中包含函數名 


def add(x,y,f):             #高階函數,函數可以傳遞函數
  return f(x) + f(y)

res = add(3,-6,abs)           #abs為python內建函數,計算絕對值
print("res=%d" %(res))
-----------------------------------------------------------------------------
res=9

=============================================================================

函數名指向函數體,將函數名傳遞給形參,形參共有函數體地址

 import time        #匯入time模組

def high1():
  time.sleep(3)      #睡眠3秒
print("this is high1")
def high2(func):
start_time=time.time()    
func()          #調用形參函數func(),實參是high1()
stop_time=time.time()
print("the func run time %s" %(stop_time-start_time)) #結束減開始時間,程式已耗用時間
high2(high1)

-----------------------------------------------------------------------------

this is high1
the func run time 3.015038013458252


=============================================================================
Python內建函數

Built-in Functions
abs() dict() help() min() setattr()
all() dir() hex() next() slice()
any() divmod() id() object() sorted()
ascii() enumerate() input() oct() staticmethod()
bin() eval() int() open() str()
bool() exec() isinstance() ord() sum()
bytearray() filter() issubclass() pow() super()
bytes() float() iter() print() tuple()
callable() format() len() property() type()
chr() frozenset() list() range() vars()
getattr() locals() repr() zip() classmethod()
compile() globals() map() reversed() __import__()
complex() hasattr() max() round()
delattr() hash() memoryview() set()

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.