您好,登錄后才能下訂單哦!
局部變量
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
免責(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)容。