지방이의 Data Science Lab

[Python] 함수 : global 변수 / 지역변수 본문

Data Analysis/Codility

[Python] 함수 : global 변수 / 지역변수

[지현] 2021. 1. 21. 17:43

파이썬 동작 원리를 알지 못할 때 머릿 속에선  

1
2
3
4
5
6
7
8
= 1
def letsthinkofglobal_a(a):
    a = a + 1
    print(a)
letsthinkofglobal_a(2)
# 3
print(a)
# 1

이렇게 되는게 이상할 것이다.

머릿속에서 생각되는

함수 자체 내에 같은 변수명을 써주더라도 함수 내에서는 지역변수라 바깥 다른 변수들에 영향을 주지 못한다.

다만 global a이런 식으로 선언을 해주면 영향을 줄 수 있다.

 

1
2
3
4
5
6
7
8
9
10
= 1
def letsthinkofglobal_a( ):
    global a
    a = a + 1
    print(a)
 
letsthinkofglobal_a( )
# 2
print(a)
# 2

이렇게 바깥에 있던 a를 2로 영향을 주고 싶을 때 사용된다.

이때 def letsthinkofglobal()부분에 a를 담으면 안된다. def letsthinkofglobal(a):

 

 

 

Comments