본문 바로가기

python

function - global, nonlocal

전역변수와 지역변수

 

global, nonlocal 활용

# 변수의 생존 범위 (scope rule)
# 변수 접근 순서 : Local > Enclosing function > Global

player = '전국대표'  # 전역변수

def funcSoccer():
    name = '신기해'  # 지역변수
    player = '전국대표'
    print(name, player)
    
funcSoccer()
# print(name)
print(player)

print('------------')
a=10; b=20; c=30
print('1) a:{}, b:{}, c:{}'.format(a,b,c))

def func1():
    a = 40
    b = 50
    c = 100
    def func2():
        # c= 60
        func2_local = 7
        global c
        nonlocal b
        print('2) a:{}, b:{}, c:{}'.format(a,b,c))
        c = 60 # local variable 'c' referenced before assignment
        b = 70
    func2()
    print('3) a:{}, b:{}, c:{}'.format(a,b,c))
    
func1()
print('함수 수행 후) a:{}, b:{}, c:{}'.format(a,b,c))

신기해 전국대표
전국대표
------------
1) a:10, b:20, c:30
2) a:40, b:50, c:30
3) a:40, b:70, c:100
함수 수행 후) a:10, b:20, c:60

'python' 카테고리의 다른 글

클로저(closure)  (0) 2022.10.06
매개변수와 인자 , 가변인수  (0) 2022.10.06
function 예제(동굴과 용 게임) - time.sleep(), random.randint()  (0) 2022.10.05
function  (0) 2022.10.05
for문, range() - 예제  (1) 2022.10.05