Python_变量作用域

回眸只為那壹抹淺笑 提交于 2019-11-29 06:27:20

1.变量作用域:

def get_apple(name,*b):
    global totalCount
    totalCount=0
    for num in b:
        print('.....................................')
        count=0
        while(count<num):
            count+=1
            totalCount+=1
            print(name+'拿第'+str(count)+'个苹果')
    return totalCount

totalCount1= get_apple('张三',5,10) #张三分两次拿苹果,第一次拿5个,第二次拿10个
print(totalCount1)
print(totalCount)

totalCount2= get_apple('李四',10,20,30) #李四分三次拿苹果,第一次拿了10个,第二次拿了20个,第三次拿了30个
print(totalCount2)
print(totalCount)

注:如果在函数体内定义的变量不加global关键字,在函数体外是无法使用这个变量的,因为它是函数体内的局部变量,加了global关键字,函数体内的局部变量就可以在函数体外使用了

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!