[python 기초] ERROR

EMMA·2022년 6월 7일
0

주요 파이썬 error list

프로그래밍의 꽃(?) 중 하나는 에러 처리다.
많은 에러가 있지만, 기초 내용 정리를 위해 작성해보는 대표적인 error list !
(정확히는 error(syntax error), exceptions로 나뉘지만 구분 없이 list up 했다)

Syntax Error
"Syntax errors, also known as parsing errors...
The parser repeats the offending line and displays a little ‘arrow’ pointing at the earliest point in the line where the error was detected." (공식문서)

Exceptions
"Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it." (공식문서)


1. Invalid syntax

for 
>>> SyntaxError: invalid syntax

2. NameError

a = b 
>>> NameError: name 'b' is not defined

3. assign to literal

  • literal: 고정된 표현값 자체를 의미함 (문자형, 숫자형, 불리언 등의 리터럴이 대표적)
  • 컬렉션 리터럴은 list/dict/set/tuple 자료형을 말함
  • None 은 특수 리터럴에 해당
100 = 'hello'
>>> SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?

4. KeyError

myDict = {'apple':3, 'orange':10, 'lemon':5}
print(myDict['grape'])
>>> KeyError: 'grape'

5. ValueError

int(3.14)
>>> ValueError: invalid literal for int() with base 10: '3.14'

6. TypeError

a = 'hello'
b = 3.14
print(a+b)
>>> TypeError: can only concatenate str (not "float") to str

7. IndexError

lst = [1,2,3]
for i in (0,5):
    print(lst[i])
>>> IndexError: list index out of range

8. ImportError : module은 존재하나 클래스/함수 등이 존재하지 않는 경우

from copy import python 
>>> ImportError: cannot import name 'python' from 'copy' (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/copy.py)

reddit에서 너무 웃겨서 갖고옴



부록) python - 변수, 상수, 리터럴

  • 변수(Variable)
    • '값'을 담는 상자 (메모리 공간)
    • 변수는 프로그래머가 사용할 메모리 주소의 임시 별명과도 같음
  • 상수(Constant)
    • 똑같은 값을 저장하는 공간
    • JAVA 등과 달리 미리 상수를 선언하는 방식은 따로 없으나, 보통 영어 대문자로만 이름을 만드는 식으로 상수임을 표시하는 컨벤션은 존재
      ("Constants are usually defined on a module level and written in all capital letters with underscores separating words. Examples include MAX_OVERFLOW and TOTAL." - PEP)
    PI = 3.14 
  • 리터럴(Literal)
    • 할당된 '값' 자체를 의미함
    • 숫자 literal: 정수 리터럴, 실수 리터럴, 복소수 리터럴
    • 바이트/문자 literal: 바이트 리터럴, 문자열 리터럴
    • 불리언 literal: boolean 리터럴 (True, False)
    • 특수 literal: None
    • 컬렉션 literal: list, tuple, set, dictionary
    myList = [1,2,3]
     myTuple = (1,2,3)
     mySet = {1,2,3}
     myDict = {'a':1, 'b':2, 'c':3}


참고 자료
파이썬 공식문서
https://wikidocs.net/20562

profile
예비 개발자의 기술 블로그 | explore, explore and explore

0개의 댓글