기다려주세요
도도동짱
전체 방문자
오늘
어제
  • 전체보기 (65)
    • Diary - Life (9)
    • Diary - IT (7)
    • Data Science (6)
    • CS & Programming (20)
    • Debugging (3)
    • Papers (10)
    • Project (3)
    • Lecture (7)

블로그 메뉴

  • 홈
  • 태그
  • 방명록
  • Github
  • Instagram

공지사항

  • 김동혁입니다 :)

인기 글

태그

  • 리눅스
  • 디버깅
  • 네이버 개발자 오픈클래스
  • polyp segmentation
  • weakly supervised learning
  • weakly supervised semantic segmentation
  • 프로젝트
  • numpay
  • Deep learning
  • WSSS
  • ubuntu
  • python
  • 파이썬
  • 알고리즘
  • 취업
  • 회고
  • 프로그래밍
  • segmentation
  • Linux
  • 개발
  • joblib
  • 빅데이터
  • Transformer
  • attribution method
  • gpt4
  • 에러
  • 일상
  • GIT
  • 투자
  • 우분투

최근 댓글

최근 글

기다려주세요

Debugging

python 에러: UnboundLocalError: local variable 'tmp' referenced before assignment

2023. 1. 2. 14:54

파이썬 코드를 짜다 보면 아래 에러를 맞이할 때가 있습니다.

UnboundLocalError: local variable 'tmp' referenced before assignment

이 말은 "tmp 라는 변수를 함수 밖에서 선언해놓고 왜 여기서 써?"라는 의미입니다.

 

 

아래 내용을 봅시다.

>>> tmp = "hi"
>>> def hi():
...     tmp = tmp + 'nice'
... 
>>> hi()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in hi
UnboundLocalError: local variable 'tmp' referenced before assignment

 

python에서 tmp라는 변수를 선언한 뒤, 함수 hi에서 tmp를 이용한 연산을 시도합니다. 그러나 tmp는 함수 밖에서 정의된 변수죠. 이런 변수를 함수 안에서 호출하면 에러가 발생합니다.

 

만약 함수 안에서 해당 변수를 사용하고 싶다면 변수 앞에 global을 붙여줍시다.

>>> tmp = "hi"
>>> def hi():
...     global tmp
...     tmp = tmp + 'nice'
... 
>>> hi()
>>> tmp
'hinice'
저작자표시 동일조건 (새창열림)

'Debugging' 카테고리의 다른 글

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() 해결법  (0) 2023.01.05
python joblib 에러: _pickle.PicklingError: Could not pickle the task to send it to the workers 해결하기  (0) 2022.12.26
도도동짱
Working on it, Walking on IT
Designed By 정상우.

티스토리툴바