python函數 一

來源:互聯網
上載者:User

標籤:python函數   lex   while   gpo   inpu   空格   元組   初識   定義函數   

函數

一。函數的初識

比如:我們測量一個字串‘asdfghj’的長度,但是不讓用len()的方法

s = ‘asdfghj‘count = 0for i in s:    count += 1print(count)

要是測量其他的字串的長度就要再次編寫這些相似的代碼,重複性強,可讀性差,此時我們可以引入函數概念。

二。函數的定義與調用

def my_len():     # def 關鍵字,定義函數   空格   函數名(變數)    s = ‘asdfghj‘    count = 0    for i in s:        count += 1    print(count)my_len()          #執行此函數

三。函數的傳回值(return)

return

1.遇到return,此函數結束,不再繼續運行(類似於迴圈中的break)

2.return有四種情況

1)不寫return               返回  None

def my_len():    s = ‘asdfghj‘    count = 0    for i in s:        count += 1ret = my_len()print(ret)                  #輸出結果 None

2)return None            返回  None

def my_len():    s = ‘asdfghj‘    count = 0    for i in s:        count += 1    return Noneret = my_len()print(ret)                  #輸出結果None

3)return 一個值          返回  此單個值

def my_len():    s = ‘asdfghj‘    count = 0    for i in s:        count += 1    return countret = my_len()print(ret)            #輸出結果:7

4)return 多個值          返回  將多個值包在元組內,返回給調用者此元組

def my_len():    ‘‘‘返回多個值‘‘‘    return count,1,3,‘alex‘,8ret = my_len()print(ret)            #輸出結果:(7, 1, 3, ‘alex‘, 8)
# 用多個值接收def my_len():    return  1,[‘a‘,‘b‘],3,4ret1,ret2,ret3,ret4 = my_len()print(ret1,ret2,ret3,ret4)# 輸出結果:1 [‘a‘, ‘b‘] 3 4

 

四。參數

實參與形參

參數還有分別:

我們調用函數時傳遞的這個“hello world”被稱為實際參數,因為這個是實際的要交給函數的內容,簡稱實參。

定義函數時的s1,只是一個變數的名字,被稱為形式參數,因為在定義函數的時候它只是一個形式,表示這裡有一個參數,簡稱形參。 

傳遞多個參數

參數可以傳遞多個,多個參數之間用逗號分割。

1.實參

從實參的角度:
1)按位置傳參

def my_line(x,y):    ‘此時x = 5 , y = 10 ‘    max =  x if x > y else y    return max#調用ma = my_line(5,10)print(ma)              #輸出結果:10

2)按關鍵字傳參

def my_len(x,y):    #x = 5 ,y = 20    max = x if x > y else y    return max#調用ma = my_len(y=20,x=5)print(ma)              #輸出結果:20

3)混合傳參         關鍵字參數永遠在位置參數後面

def my_len(x,y):    #x = 5,y = 15    max = x if x > y else y    return max#調用ma = my_len(5,y=15)print(ma)             #輸出結果:20

2.形參

1)位置參數

def mymax(x,y):    #此時x=10,y=20    the_max = x if x > y else y    return the_maxma = mymax(10,20)print(ma)             #輸出結果:20

2)預設參數

def fa(name,sex=‘男‘):    with open(‘name_list‘,‘a‘,encoding=‘utf-8‘) as f:        f.write(‘{},{}\n‘.format(name,sex))while 1:    name = input(‘請輸入姓名:‘)    if ‘姐‘ in name:        sex = input(‘請輸入性別:‘)        fa(name,sex)    else:        fa(name)

 

python函數 一

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.