728x90
반응형
"Life is too short, You need python"
UnboundLocalError: local variable referenced before assignment 에러는 흔히 볼 수 있는 오류입니다. 어떤 에러이고 어떻게 해결해야 할지 알아보겠습니다.
UnboundLocalError: local variable referenced before assignment
UnboundLocalError: local variable referenced before assignment
: 할당 전에 참조된 로컬 변수
원인
일반적으로 코드가 전역 변수에 액세스하려고 할 때 발생합니다. 변수는 기본적으로 항상 로컬로 간주됩니다. 따라서 프로그램이 전역 변수를 지정하지 않고 함수 내의 전역 변수에 액세스 하려고 하면 참조되는 변수가 지역 변수로 간주되므로 코드는 할당 전에 참조된 지역 변수 오류를 반환합니다.
( Input )
count = 10
def myfunc():
count = count + 1
print(count)
myfunc()
( Output )
UnboundLocalError: local variable 'count' referenced before assignment
해결 방법
Python에서 global키워드를 사용하여 변수를 전역으로 선언할 수 있습니다. 변수가 전역으로 선언되면 프로그램은 함수 내에서 변수에 액세스 할 수 있으며 오류가 발생하지 않습니다.
( Input )
count = 10
def myfunc():
global count
count = count + 1
print(count)
myfunc()
( Output )
11
마무리
UnboundLocalError: local variable referenced before assignment 에러의 원인과 해결 방법에 대해 알아보았습니다.
728x90
반응형