Python學(xué)習(xí)筆記——Python 函數(shù)

1. 函數(shù)定義與調(diào)用

def MyFirstFunction():
    print('這是我創(chuàng)建的第一個函數(shù)')
#調(diào)用
MyFirstFunction()
這是我創(chuàng)建的第一個函數(shù)

2. 函數(shù)文檔

def MySecondFunction(name):
    #下面這個字符串即為函數(shù)文檔
    '函數(shù)定義過程中的name叫形參'
    print('你的名字是' + name)
MySecondFunction('Nigream')
#兩個雙下劃線表示系統(tǒng)屬性
print(MySecondFunction.__doc__)
#也可以用
help(MySecondFunction)
你的名字是Nigream
函數(shù)定義過程中的name叫形參
Help on function MySecondFunction in module __main__:

MySecondFunction(name)
    函數(shù)定義過程中的name叫形參

?

3. 關(guān)鍵字參數(shù)

def SaySome(name , words):
    print(name + '-->' + words)
SaySome(name='Nigream',words='hello')
Nigream-->hello

4. 默認參數(shù)

def SaySome(name = 'Nigream', words = 'hello'):
    print(name + '-->' + words)
SaySome()
SaySome('蒼井空')
SaySome('蒼井空' , '我脫光衣服躺在鏡頭前,是為了生存;而你衣冠楚楚地站在鏡頭前贾节,卻是為了私欲和欺騙蝌麸!')
Nigream-->hello
蒼井空-->hello
蒼井空-->我脫光衣服躺在鏡頭前颓影,是為了生存雌续;而你衣冠楚楚地站在鏡頭前,卻是為了私欲和欺騙熏迹!

5. 收集參數(shù)

def test(*params):
    print('參數(shù)的長度是:',len(params))
    print('第三個參數(shù)是:',params[2])

test(1,2,3,4,'Nigream',5)
參數(shù)的長度是: 6
第三個參數(shù)是: 3

6. 返回值

def back():
    return [1,'Nigream',3.14]
print(back())
#運行結(jié)果
[1, 'Nigream', 3.14]
def back1():
    return 1,'Nigream',3.14
#這里被看成一個元組
print(back1())
[1, 'Nigream', 3.14]
(1, 'Nigream', 3.14)

7. 作用域

def discounts(price,rate):
    final_price = price * rate
    return final_price

old_price = float(input('請輸入原價:'))
rate = float(input('請輸入折扣率:'))
new_price = discounts(old_price,rate)
print('打折后的價格是:',new_price)
請輸入原價:100
請輸入折扣率:0.8
打折后的價格是: 80.0
def discounts(price,rate):
    final_price = price * rate
    return final_price

old_price = float(input('請輸入原價:'))
rate = float(input('請輸入折扣率:'))
new_price = discounts(old_price,rate)
print('打折后的價格是:',new_price)
print('這里試圖打印局部變量final_price的值:',final_price)
請輸入原價:100
請輸入折扣率:0.8
打折后的價格是: 80.0
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-9-bd414db96855> in <module>()
      7 new_price = discounts(old_price,rate)
      8 print('打折后的價格是:',new_price)
----> 9 print('這里試圖打印局部變量final_price的值:',final_price)

NameError: name 'final_price' is not defined
def discounts(price,rate):
    final_price = price * rate
    print('這里試圖打印全局變量old_price的值:',old_price)
    return final_price

old_price = float(input('請輸入原價:'))
rate = float(input('請輸入折扣率:'))
new_price = discounts(old_price,rate)
print('打折后的價格是:',new_price)
請輸入原價:100
請輸入折扣率:0.8
這里試圖打印局部變量old_price的值: 100.0
打折后的價格是: 80.0
def discounts(price,rate):
    final_price = price * rate
    #在這里python會重新定義一個名字相同的局部變量
    old_price = 50
    print('這里試圖打印局部變量old_price的1值:',old_price)
    return final_price

old_price = float(input('請輸入原價:'))
rate = float(input('請輸入折扣率:'))
new_price = discounts(old_price,rate)
print('這里試圖打印全局變量old_price的2值:',old_price)
print('打折后的價格是:',new_price)
請輸入原價:100
請輸入折扣率:0.8
這里試圖打印局部變量old_price的1值: 50
這里試圖打印全局變量old_price的2值: 100.0
打折后的價格是: 80.0

8. global

count = 5
def MyFun():
    count = 10
    print(10)
MyFun()
print(count)
10
5
#要在函數(shù)內(nèi)部修改count
count = 5
def MyFun():
    global count
    count = 10
    print(10)
MyFun()
print(count)
10
10

9. 內(nèi)嵌函數(shù)

def fun1():
    print('fun1正在被調(diào)用')
    def fun2():
        print('fun2正在被調(diào)用')
    fun2()
fun1()
fun1正在被調(diào)用
fun2正在被調(diào)用

10. 閉包

#如果在一個內(nèi)部函數(shù)里辑甜,對在外部作用域(但不是在全局作用域)的變量
#進行引用衰絮,那么內(nèi)部函數(shù)就被認為是閉包(closure)。
def FunX(x):
    def FunY(y):
        return x*y
    return FunY
i = FunX(8)
print(type(i))

print(i(5))
print(FunX(8)(5))
<class 'function'>
40
40
def Fun1():
    x = 5
    def Fun2():
        #這里由于外層作用域已經(jīng)定義了x磷醋,
        #所以此時系統(tǒng)會重新定義局部變量x猫牡,
        #而又未次局部變量賦值,所以該x = x + 2會報錯
        x *= x
        return x
    return Fun2()

Fun1()
---------------------------------------------------------------------------

UnboundLocalError                         Traceback (most recent call last)

<ipython-input-32-d753abbbddb3> in <module>()
      9     return Fun2()
     10 
---> 11 Fun1()

<ipython-input-32-d753abbbddb3> in Fun1()
      7         x *= x
      8         return x
----> 9     return Fun2()
     10 
     11 Fun1()

<ipython-input-32-d753abbbddb3> in Fun2()
      5         #所以此時系統(tǒng)會重新定義局部變量x邓线,
      6         #而又未次局部變量賦值淌友,所以該x = x + 2會報錯
----> 7         x *= x
      8         return x
      9     return Fun2()

UnboundLocalError: local variable 'x' referenced before assignment
#python2解決,利用列表等容器
def Fun1():
    #將其定義為列表
    x = [5]
    def Fun2():
        x[0] *= x[0]
        return x[0]
    return Fun2()

Fun1()
25
#python3解決骇陈,利用關(guān)鍵字nonlocal
def Fun1():
    x = 5
    def Fun2():
        nonlocal x
        x *= x
        return x
    return Fun2()

Fun1()
25
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末震庭,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子你雌,更是在濱河造成了極大的恐慌器联,老刑警劉巖二汛,帶你破解...
    沈念sama閱讀 216,402評論 6 499
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異拨拓,居然都是意外死亡肴颊,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,377評論 3 392
  • 文/潘曉璐 我一進店門渣磷,熙熙樓的掌柜王于貴愁眉苦臉地迎上來婿着,“玉大人,你說我怎么就攤上這事醋界【顾危” “怎么了?”我有些...
    開封第一講書人閱讀 162,483評論 0 353
  • 文/不壞的土叔 我叫張陵物独,是天一觀的道長袜硫。 經(jīng)常有香客問我氯葬,道長挡篓,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,165評論 1 292
  • 正文 為了忘掉前任帚称,我火速辦了婚禮官研,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘闯睹。我一直安慰自己戏羽,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,176評論 6 388
  • 文/花漫 我一把揭開白布楼吃。 她就那樣靜靜地躺著始花,像睡著了一般。 火紅的嫁衣襯著肌膚如雪孩锡。 梳的紋絲不亂的頭發(fā)上酷宵,一...
    開封第一講書人閱讀 51,146評論 1 297
  • 那天,我揣著相機與錄音躬窜,去河邊找鬼浇垦。 笑死,一個胖子當(dāng)著我的面吹牛荣挨,可吹牛的內(nèi)容都是我干的男韧。 我是一名探鬼主播,決...
    沈念sama閱讀 40,032評論 3 417
  • 文/蒼蘭香墨 我猛地睜開眼默垄,長吁一口氣:“原來是場噩夢啊……” “哼此虑!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起口锭,我...
    開封第一講書人閱讀 38,896評論 0 274
  • 序言:老撾萬榮一對情侶失蹤寡壮,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體况既,經(jīng)...
    沈念sama閱讀 45,311評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡这溅,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,536評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了棒仍。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片悲靴。...
    茶點故事閱讀 39,696評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖莫其,靈堂內(nèi)的尸體忽然破棺而出癞尚,到底是詐尸還是另有隱情,我是刑警寧澤乱陡,帶...
    沈念sama閱讀 35,413評論 5 343
  • 正文 年R本政府宣布浇揩,位于F島的核電站,受9級特大地震影響憨颠,放射性物質(zhì)發(fā)生泄漏胳徽。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,008評論 3 325
  • 文/蒙蒙 一爽彤、第九天 我趴在偏房一處隱蔽的房頂上張望养盗。 院中可真熱鬧,春花似錦适篙、人聲如沸往核。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,659評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽聂儒。三九已至,卻和暖如春硫痰,著一層夾襖步出監(jiān)牢的瞬間衩婚,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,815評論 1 269
  • 我被黑心中介騙來泰國打工碍论, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留谅猾,地道東北人。 一個月前我還...
    沈念sama閱讀 47,698評論 2 368
  • 正文 我出身青樓鳍悠,卻偏偏與公主長得像税娜,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子藏研,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,592評論 2 353