1. 국내주식/1-4. 오류 해결

(파이썬) TypeError: unsupported operand type(s) for /: 'str' and 'int'

봄이오네 2022. 9. 23. 08:06
반응형

1. 들어가며

파이썬에서는 문자형은 문자형, 인자형은 인자형끼리 문장이 이루어진다.

문자형(str) 및 인자형(in)을 더하거나 빼면 아래의 에러가 발생한다.


2. 오류 예시

a = "100"

print(a/4)


(expect result)

Traceback (most recent call last):
  File "C:\Users\User\Desktop\pythonProject\str vs int.py", line 3, in <module>
    print(a/4)
TypeError: unsupported operand type(s) for /: 'str' and 'int'

3. 오류 해결

문자형으로 선언된 a를 인자형으로 변경한다.

 ※ 문자형으로 선언되었다는 것은 숫자 100의 양 옆으로 쌍 따옴표(" ")가 붙었다는 내용이다.

 

이때는, a=100 혹은 a=int("100")으로 변경해준다.

a = 100
print(a/4)

b = int("100")
print(b/4)

(expected resul)
25.0
25.0

4. 기타 : 문자형과 관련된 추가 오류 (사칙연산)

 ㅇ 에러 내용 : TypeError: can only concatenate str (not "int") to str

a = "100"
print(a+4)

(expected resul)
:\Users\User\anaconda3\python.exe "C:/Users/User/Desktop/pythonProject/str vs int.py" 
Traceback (most recent call last):
  File "C:\Users\User\Desktop\pythonProject\str vs int.py", line 2, in <module>
    print(a+4)
TypeError: can only concatenate str (not "int") to str

 

 ㅇ 에러 원인 : "int"(인트형을 문자형으로 바꾸어 줌)이 아니면, 문자형은 문자형과 연결된다.

 ㅇ 에러 해결 : 문자형으로 선언된 a를 인수형으로 변경하거나, 쌍 따옴표(" ")를 없애준다

a = 100
print(a+4)

(resulted result)
104

5. 마치며

2가지 에러 모두 문자형과 인자형을 더하거나 나누어서 에러가 발생하였다.

 1) TypeError: unsupported operand type(s) for /: 'str' and 'int'

 2) TypeError: can only concatenate str (not "int") to str

 

키움 KOA Studio에서 확인해 보았듯이,

키움증권의 OpenAPI가 우리에게 제공하는 데이터는 문자형이다.

위의 2가지 에러가 발생한 경우, 양립할 수 없는 형태가,

더하거나, 빼거나, 곱하거나, 나눌 때 쓰이고 있다.

 

키움증권에서 받아오는 형태(문자형 혹은 인자형)에 대해

에러발생의 최소화를 위해 형태를 파악해 두는 습관을 들일 필요가 있다.

 

 

반응형