-
python main함수 변수Python/기초 2021. 10. 20. 14:56
1. 전역 변수 참조
def A(): print(cnt) #1 def B(): if cnt == 5: #2 print(cnt) #3 if __name__ == "__main__": cnt = 5 A() B() print(cnt)
- python에서 main에서 선언한 변수의 경우 전역변수가 된다.
- 함수 A, B에서 cnt가 자신의 함수에서 선언한 지역변수인지 우선 확인한다.
- 함수 내에서 선언한 경우가 없을 경우 전역변수로 사용한다.(main에서도 cnt를 선언하지 않았을 경우는 에러가 발생)
- A,B 모두 cnt를 선언한 적이 없기 때문에 #1, #2, #3 모두 main에서 선언한 전역변수 cnt를 참조한다.
출처: https://www.landlordgang.xyz/26
728x90'Python > 기초' 카테고리의 다른 글
int.from_bytes python (0) 2021.10.22 list 나눠서 출력 (0) 2021.10.20 zip() 함수 (0) 2021.10.19 메모리 주소값 불러오는 함수 id() (0) 2021.10.18 Python - List (0) 2021.10.15 댓글