250x250
250x250
  • 분류 전체보기 (48)
    • Save Your TIME (1)
      • WORK SMART - RPA (0)
      • 비 전공 직장인의 업무 자동화 고군분투기 (1)
    • Make a lot of MONEY (0)
      • 부동산 (0)
    • PYTHON (45)
      • BASIC (3)
      • pandas (3)
      • tkinter (8)
      • LIBRARY | ETC (1)
      • Tips (19)
      • Error Solutions (11)
    • EXCEL (0)
      • BASIC (0)
      • TIP (0)
    • Life & Education (2)
      • 초등 수학 (2)
      • English (0)
    • TISTORY (0)
      • ABOUT BLOG (0)
      • TIP (0)
    • Reference (0)
hELLO · Designed By 정상우.
Creatio ex nihilo

Py Life

(Python/Pandas) UnboundLocalError: local variable referenced before assignment
PYTHON/Error Solutions

(Python/Pandas) UnboundLocalError: local variable referenced before assignment

2022. 7. 7. 17:35
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
반응형
저작자표시 비영리 변경금지 (새창열림)

'PYTHON > Error Solutions' 카테고리의 다른 글

(Python/Pandas) Python Import Error / Module Not Found Error 해결 방법  (0) 2024.01.18
(Python/Tkinter) Listbox 외부 Index Error: tuple index out of range  (0) 2022.07.21
(Python/OS, Pandas) open, read file PermissionError: [Errno 13] Permission denied:  (0) 2022.06.30
(Python/Pandas) UnicodeDecodeError: 'utf-8' codec can't decode byte 유니코드 디코드 에러(오류)  (0) 2022.06.27
(Python/Pandas) ParserError: Error tokenizing data. read_csv 파싱 에러(오류)  (0) 2022.06.27
    Creatio ex nihilo
    Creatio ex nihilo
    "Life is too short, You need python"

    티스토리툴바