两个不同函数内部的变量名可以一样

2018-10-25  本文已影响0人  愿你有闯荡风雪的骁勇

def local1():

    num1=100

    print("local1中的num1的值位:%d"%num1)

def local2():

    num=102

    print("local2中num2的值位:%d"%num)

local1()

local2()

#总之,就是两个不同函数内部的变量名可以一样。

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

函数之内有这个变量result=100的,函数以外的相同的变量就不用了

def sum(a,b):

result=a+b

print("函数内的result的值为:",result)

sum(100,20)

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

这种确实是不行啊,函数之内确实不能用函数之外的变量

UnboundLocalError: local variable 'a' referenced before assignment

unbound英['ʌn'baʊnd]美[ʌnˈbaʊnd]

adj.无束缚的; <正>不负有义务的;

v.解开,解放( unbind的过去式和过去分词 );

Many cultures still have fairly strict rules about women displaying unbound hair.

许多文化中对女子披散头发仍有着相当严格的规定。

a=1000

def test():

a+=1

    print(a)

test()

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

global关键字来了。scale英[skeɪl]美[skel]

n.规模; 比例(尺); 鱼鳞; 级别;

vt.测量; 攀登; 刮去…的鳞片;

vi.衡量; 攀登; (鳞屑) 脱落; 生水垢;

[例句]However, he underestimates the scale of the problem

然而,他低估了问题的严重性。

On a global scale, AIDS may well become the leading cause of infant death.

艾滋病很可能会成为造成全球婴儿死亡的首要原因。

a=1000#就是a完全可以当参数传进来啊 !!!!不一定非要global

def test(a):

a+=1

    print(a)

test(a)

---------

a=1000

def test():

    global a

    a+=1

    print(a)

test()

——————-----------------------------------------------------------

使用nonlocal关键字可以在一个嵌套的函数中修改嵌套作用域中的变量

def test():

    x=1

    def test2():

        x=2

    test2()

    print(x)

test()

#输出1

#这样是正常啊,虽然在第二个函数中也定义了x=2,并且进行了调用。但是是并列啊,就是和前面那个x=1是并列,不报错已经不错了,肯定是按第一个x=1

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

def test():

x=1

    def test2():

nonlocal x

x=2

    test2()

print(x)

test()

#输出2

就是不再是本地的变量了,nonlocal 了嘛

上一篇 下一篇

猜你喜欢

热点阅读