250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- glob
- __sub__
- MySqlDB
- 오버라이딩
- __getitem__
- decode()
- randrange()
- shuffle()
- discard()
- node.js
- __len__
- items()
- MySQL
- shutil
- Database
- remove()
- HTML
- locals()
- count()
- View
- zipfile
- fileinput
- mro()
- inplace()
- 파이썬
- fnmatch
- CSS
- choice()
- __annotations__
- JS
Archives
- Today
- Total
흰둥이는 코드를 짤 때 짖어 (왈!왈!왈!왈!왈!왈!왈!왈!왈!왈!왈!)
(파이썬) 변수의 범위 본문
728x90
반응형
1. 스코프(scope)
- 변수의 접근할 수 있는 범위
- local: 가장 가까운 함수안의 범위
- global: 함수 바깥의 변수 또는 import된 module
In [1]:
num1 = 10 # 글로벌 변수
def func1():
num2 = 20 # 로컬 변수
print(num2)
In [2]:
print(num1)
print(num2) # NameError: name 'num2' is not defined
10
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-2-235389bf156e> in <module>
1 print(num1)
----> 2 print(num2)
NameError: name 'num2' is not defined
In [3]:
num1 = 10
def func1():
num2 = 20
print(num2)
In [4]:
print(num1)
func1()
10
20
In [13]:
# locals(): 로컬 변수를 확인해주는 함수
# globals(): 글로벌 변수를 확인해주는 함수
num1 = 10 # 글로벌 변수
def func1():
num2 = 20 # 로컬 변수
print('num1 로컬 변수: ', 'num1' in locals())
def func2():
num2 = 20 # 로컬 변수
print('num2 로컬 변수: ', 'num2' in locals())
def func3():
print('num1 글로벌 변수: ', 'num1' in globals())
In [9]:
func1()
num1 로컬 변수: False
In [11]:
func2()
num2 로컬 변수: True
In [14]:
func3()
num1 글로벌 변수: True
In [16]:
num1 = 10
def func4():
num1 = 20 # 지역 변수
print(num1)
In [18]:
func4()
20
In [19]:
print(num1) # 전역 변수
10
2. global 키워드
- 함수 내부에서 로컬변수가 아닌 글로벌 변수로 사용하게 함
In [25]:
num1 = 10
def func5():
print(num1)
def func6(num):
num1 = num # 로컬변수에 값을 저장했으므로 글로벌 변수에 값이 변경되지 않음
In [22]:
func5()
10
In [23]:
func6(5)
In [24]:
func5()
10
In [26]:
num1 = 10
def func5():
print(num1)
def func6(num):
global num1
num1 = num
In [27]:
func5()
10
In [28]:
func6(5)
In [29]:
func5()
5
728x90
반응형
'파이썬 기초' 카테고리의 다른 글
(파이썬) 랜덤 모듈 (0) | 2023.03.09 |
---|---|
(파이썬) Callback 함수와 Lambda 함수 (0) | 2023.03.09 |
(파이썬) 사용자 정의 함수 (0) | 2023.03.08 |
(파이썬) 세트 (0) | 2023.03.08 |
(파이썬) 딕셔너리 (0) | 2023.03.08 |
Comments