溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python內(nèi)嵌函數(shù)

發(fā)布時(shí)間:2020-07-27 16:58:31 來(lái)源:網(wǎng)絡(luò) 閱讀:275 作者:aurtherconan 欄目:編程語(yǔ)言

局部變量

def discount(price, rate):

final_price = price * rate

return final_price


old_price = float(input('請(qǐng)輸入原價(jià):'))    全局變量

rate = float(input('請(qǐng)輸入折扣率:'))

new_price = discount(old_price, rate)

print('打折后的價(jià)格是:',new_price)

print('打印局部變量final_price的值:',final_price) 顯示為定義的變量,final_price為discount函數(shù)中的變量,為局部變量,出了discount就無(wú)效了  


在局部變量中定義全局變量

>>> test1 = 5

>>> def change():

test1 = 10

print(test1)


>>> change()

10

>>> test1

5


>>> def change():

global test1

test1 = 10

print(test1)


>>> change()

10

>>> test1

10


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

>>> def fun1():

print('fun1正在被調(diào)用..')

def fun2():

print('fun2正在被調(diào)用...')

fun2()


>>> fun1()        調(diào)用fun1()后執(zhí)行調(diào)用fun2()

fun1正在被調(diào)用..

fun2正在被調(diào)用...


閉包 如果在一個(gè)內(nèi)部函數(shù)里,對(duì)在外部作用域的變量進(jìn)行引用

>>> def fun3(x):

def fun4(y):

return x * y

return fun4


>>> fun3(1)

<function fun3.<locals>.fun4 at 0x0000000002F549D8>

>>> type(fun3)

<class 'function'>


>>> fun3(1)(2)

2


>>> def fun1():

x = 5

def fun2():

x *= x

return x

return fun2()

>>> fun1()

Traceback (most recent call last):

  File "<pyshell#52>", line 1, in <module>

    fun1()

  File "<pyshell#50>", line 6, in fun1

    return fun2()

  File "<pyshell#50>", line 4, in fun2

    x *= x

UnboundLocalError: local variable 'x' referenced before assignment


>>> def fun1():

x = 5

def fun2():

nonlocal x    強(qiáng)制聲明非局部變量

x *= x

return x

return fun2()

>>> fun1()

25










向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI