본문 바로가기
프로그래밍/Python

[Python] 에러모음 및 해결방법

by JR2 2021. 3. 13.

에러 : Indetation Error : IndentationError: expected an indented block

 

원인 : 들여쓰기

python은 인터프리터 언어이다. 따라서 한줄 씩 코드를 읽어가는데,

다른문법과 달리 세미콜론(;)이 없이, 들여쓰기로 명령어의 끝을 알린다.

따라서 들여쓰기가 굉장히 중요하다.

 

해결방법 : 들여쓰기를 제대로 하였는지 확인해보아야 한다.

 

 


 

에러 : syntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

 

원인 : \, / 를 잘못 쓴 경우

 

해결방법 :

예를 들어 이렇게 작성이 되어있는 코드에서 에러가 났다면

"C:\Users\jh\Desktop\ExamSelenium"

=>

"C:/Users/jh/Desktop/ExamSelenium"

 

이렇게 바꾸어 본다.

 

 


 

 

에러 : TypeError:listtypeError: can only concatenate str (not "int") to str

 

원인 : 출력할 때, 문자와 숫자가 합쳐있는 경우

a = 100
b = "100"

print(a + "는 정수입니다.")
print(b + "는 정수입니다.")

print(a + b)

이런식으로 자료형이 뒤 섞여서 발생한 에러이다.

 

해결방법 : 아래와 같이 혼동이 생길만한 곳에 자료형 변환을 해주면 된다.

a = 100
b = "100"

print(str(a) + "는 정수입니다.")
print(b + "는 정수입니다.")

print(a + int(b))

 


 

 

에러 : list indices must be integers or slices, not str

 

원인 : 현재 사용하는 변수가 이미 str 타입인데, int라고 착각하고 배열에서 호출하는 경우

a = ["hi", "my", "name", "is", "genius"]

for i in a:
    print(a[i])

이게 뭐가 잘못됐나??? C언어 문법에 익숙한 사람은 그렇게 착각할 수 있다.

 

해결방안 :  하지만 파이썬에서는 그렇게 사용하는게 아니라 이렇게 아주 간단히 사용하면 된다.

a = ["hi", "my", "name", "is", "genius"]

for i in a:
    print(i)

 

 


 

 

에러 : syntaxError: cannot assign to conditional expression

 

원인 : if문을 문법과 다르게 사용해서 나는 에러.

a = 5
b = 7
c = 9

max = a if(a>b and a>c) else max = b if(b>c) else max = c

print(max)

이렇게 쓰면 안됨.

 

해결방안 : 

a = 5
b = 7
c = 9

max = a if(a>b and a>c) else b if(b>c) else c

print(max)

이렇게 사용해야함. = 등호가 1개가 들어가야함.

복잡하게 여러개 사용하고 싶다고 하면, if a>b : 으로 줄바꿈으로 작성해야한다.

 


 

현상 :
    입력 : pip install request

에러 : 
ERROR: Could not find a version that satisfies the requirement request (from versions: none)
ERROR: No matching distribution found for request

 

해결방법 : 

1. pip3 install --upgrade pip 입력

2. pip install request입력. (s를 꼭 붙혔어야했다..)

 


 

댓글