Python学習チャンネル by PyQ

Pythonのオンライン学習プラットフォームPyQのオフィシャルブログです

TypeError: unsupported operand type(s) for /: 'str' and 'int' のエラーメッセージでお困りですか?

こんにちは、PyQサポートです。

今回は、 TypeError: unsupported operand type(s) for /: 'str' and 'int' というエラーの意味と考えられる原因を紹介します。

TypeError: unsupported operand type(s) for /: 'str' and 'int' のエラーの意味と対処法

以下のように、文字列扱いの数値が代入されている変数 num1 を使って、 num1 / 100 のように演算子 / を使って割り算を行うと、エラー TypeError: unsupported operand type(s) for /: 'str' and 'int' が発生します。
これは、「演算子 / に文字列(str)と整数(int)の計算は想定されていない」という意味のエラーです。

>>> num1 = "200"
>>> num1 / 100
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'

数値同士で / 演算子を使うと割り算が実行されます。
このエラーが発生したときは 「数値のつもりだったのに文字列だった」 ことがエラーの原因と考えられます。
文字列が変数に代入される可能性がある場合は、 float() または int() を使うとこのエラーを回避できます。

>>> float(num1) /100
2.0

変数の型を確認する

以下の変数 num1num2print() すると両方 200 と表示されてしまいます。
変数の型を確認するには、 type() を使います。
type() を使うと変数に代入されている値の型がわかります。

>>> num1 = "200"
>>> num2 = 200
>>> print(num1, num2)
200 200
>>> type(num1)
<class 'str'>
>>> type(num2)
<class 'int'>

似たようなエラーの紹介

同じようなエラーを紹介します。

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

また、文字列同士で演算子 / を使用しても同じようなエラーが発生します。

>>> "ABC" / "x"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'str'

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

他にも、リストと整数で演算子 / を使用しても同じようなエラーが発生します。

>>> [1, 2, 3]/10
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'list' and 'int'

まとめ

エラー TypeError: unsupported operand type(s) for /: 'xxx' and 'yyy' は、割り算に演算子 /を使うとき、演算対象の値の型が、 int でも float でもない場合に発生します。

Copyright ©2017- BeProud Inc. All rights reserved.