[Python]UnboundLocalError: cannot access local variable 'result' where it is not associated with a value
2025/4/21 업데이트
이유
UnboundLocalError에서 local variable 'result'가 없다는 뜻은
result라는 지역변수를 초기할당 해주지 않았다는 의미이다.
해결
result가
스트링이면 result = '', 정수면 result = 0 이런 식으로 할당을 해두자.
예전에 쓴 글
11/21
상황
모듈 내에 있는 함수가 이런 형태이다.
def function(param):
#변수
def function(param):
return result
def function(param):
return result
return result
근데 자체 프로그램으로 돌릴 때 즉
python3 module.py
하면 결과가 잘 나오는데
import 되는 모듈로서 돌릴 때는 왜인지 에러가 떴다.
UnboundLocalError: cannot access local variable 'result' where it is not associated with a value
해결
def function(param):
#변수
result = 0 # <---추가
def function(param):
result = 0
return result # <---추가
def function(param):
result = 0
return result # <---추가
return result
고민을 많이 했다.
https://www.folivoralab.com/265
파이썬 "UnboundLocalError: local variable 'time' referenced before assignment"
파이썬에서 현재 timestamp를 얻기 위해 보통 import time을 하고 time.time() 함수를 호출한다. 그런데 UnboundLocalError: local variable 'time' referenced before assignment 라는 에러가 계속 발생했다. 수천번을 문제없
www.folivoralab.com
위 블로그 참고해보니
result라는 변수를 남용했나 싶어서
return result, return fin_result 이런 식으로 변수명을 바꾸려다가
변수는 어차피 재사용이 가능하기 때문에
그건 상관 없다는 생각이 들어서 다시 찾아봤다.
결국 아래 블로그를 참고해서 해결했다.
해결 블로그
https://pylife.tistory.com/entry/PythonPandas-UnboundLocalError-local-variable-referenced-before-assignment
(Python/Pandas) UnboundLocalError: local variable referenced before assignment
"Life is too short, You need python" UnboundLocalError: local variable referenced before assignment 에러는 흔히 볼 수 있는 오류입니다. 어떤 에러이고 어떻게 해결해야 할지 알아보겠습니다. UnboundLocalError: local variable
pylife.tistory.com