Guidelines

UnboundLocalError μ—λŸ¬μ™€ μ˜ˆμ™Έ 처리 방법

UnboundLocalErrorλŠ” 지역 λ³€μˆ˜(Local variable)λ₯Ό μ°Έμ‘°ν•˜λ €κ³  ν–ˆμœΌλ‚˜, ν•΄λ‹Ή λ³€μˆ˜κ°€ 아직 ν• λ‹Ήλ˜μ§€ μ•Šμ€ κ²½μš°μ— λ°œμƒν•˜λŠ” μ˜ˆμ™Έμž…λ‹ˆλ‹€.

νŒŒμ΄μ¬μ—μ„œ ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ μ„ μ–Έλœ λ³€μˆ˜λŠ” 지역 λ³€μˆ˜λ‘œ κ°„μ£Όλ©λ‹ˆλ‹€. ν•¨μˆ˜ 외뢀에 같은 μ΄λ¦„μ˜ λ³€μˆ˜κ°€ μ„ μ–Έλ˜μ–΄ μžˆμ–΄λ„ ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ λ³€μˆ˜λ₯Ό μ°Έμ‘°ν•  λ•ŒλŠ” 지역 λ³€μˆ˜λ‘œ κ°„μ£Όλ©λ‹ˆλ‹€.


UnboundLocalError λ°œμƒ μ˜ˆμ‹œ
counter = 0 # μ „μ—­ λ³€μˆ˜ def increase_counter(): # UnboundLocalError λ°œμƒ counter += 1 return counter print(increase_counter())

μœ„ μ½”λ“œ μ˜ˆμ‹œμ—μ„œ ν•¨μˆ˜ 외뢀에 μ„ μ–Έλœ counter μ „μ—­(Global) λ³€μˆ˜μ™€ increase_counter ν•¨μˆ˜ λ‚΄λΆ€μ˜ counter 지역(Local) λ³€μˆ˜λŠ” μ„œλ‘œ λ‹€λ₯Έ λ³€μˆ˜λ‘œ μΈμ‹λ©λ‹ˆλ‹€.

λ”°λΌμ„œ ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ counter λ³€μˆ˜λ₯Ό μ°Έμ‘°ν•˜λ €κ³  ν•˜λ©΄, ν•΄λ‹Ή λ³€μˆ˜κ°€ 아직 ν• λ‹Ήλ˜μ§€ μ•Šμ•˜κΈ° λ•Œλ¬Έμ— UnboundLocalError μ˜ˆμ™Έκ°€ λ°œμƒν•©λ‹ˆλ‹€.


μœ„ μ˜ˆμ‹œμ—μ„œ counter λ³€μˆ˜λ₯Ό μ „μ—­ λ³€μˆ˜λ‘œ μ‚¬μš©ν•˜λ €λ©΄ global ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν•΄μ•Ό ν•©λ‹ˆλ‹€.

UnboundLocalError ν•΄κ²° 방법
counter = 0 # μ „μ—­ λ³€μˆ˜ def increase_counter(): # μ „μ—­ λ³€μˆ˜λ‘œ μ‚¬μš© global counter counter += 1 return counter print(increase_counter())

μœ„ μ½”λ“œμ—μ„œ increase_counter ν•¨μˆ˜ λ‚΄ counter λ³€μˆ˜λ₯Ό μ „μ—­ λ³€μˆ˜λ‘œ μ‚¬μš©ν•˜κΈ° μœ„ν•΄ global ν‚€μ›Œλ“œλ₯Ό μ‚¬μš©ν–ˆμŠ΅λ‹ˆλ‹€.


UnboundLocalError μ˜ˆμ™Έλ₯Ό μ²˜λ¦¬ν•˜λ €λ©΄ μ–΄λ–»κ²Œ ν•΄μ•Ό ν• κΉŒμš”?

κ°€μž₯ 일반적인 λ°©λ²•μœΌλ‘œλŠ” try-except 문을 μ‚¬μš©ν•΄ UnboundLocalError μ˜ˆμ™Έλ₯Ό μ²˜λ¦¬ν•  수 μžˆμŠ΅λ‹ˆλ‹€.

UnboundLocalError μ˜ˆμ™Έ 처리
counter = 0 # μ „μ—­ λ³€μˆ˜ def increase_counter(): try: counter += 1 except UnboundLocalError as e: print(f'UnboundLocalError λ°œμƒ: {e}') return counter print(increase_counter())

μœ„ μ½”λ“œμ—μ„œ increase_counter ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ counter λ³€μˆ˜λ₯Ό μ°Έμ‘°ν•  λ•Œ UnboundLocalError μ˜ˆμ™Έκ°€ λ°œμƒν•˜λ©΄, except λΈ”λ‘μ—μ„œ μ˜ˆμ™Έλ₯Ό μ²˜λ¦¬ν•˜κ³  λ©”μ‹œμ§€λ₯Ό 좜λ ₯ν•©λ‹ˆλ‹€.

UnboundLocalError μ˜ˆμ™ΈλŠ” 주둜 μ „μ—­ λ³€μˆ˜μ™€ 지역 λ³€μˆ˜λ₯Ό ν˜Όλ™ν•˜μ—¬ λ°œμƒν•˜λŠ” κ²½μš°κ°€ λ§ŽμœΌλ―€λ‘œ, ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ λ³€μˆ˜λ₯Ό μ°Έμ‘°ν•  λ•Œ μ£Όμ˜ν•΄μ•Ό ν•©λ‹ˆλ‹€.

Mission
0 / 1

UnboundLocalErrorλŠ” ν•¨μˆ˜ λ‚΄λΆ€μ—μ„œ μ΄ˆκΈ°ν™”λ˜μ§€ μ•Šμ€ 지역 λ³€μˆ˜λ₯Ό μ°Έμ‘°ν•  λ•Œ λ°œμƒν•œλ‹€.

O
X

Guidelines

AI Tutor

Publish

Design

Upload

Notes

Favorites

Help

Code Editor

Run
Generate

Execution Result