のんびりしているエンジニアの日記

ソフトウェアなどのエンジニア的な何かを書きます。

Python エラーコードまとめ(KeyError,TypeError,AttributeError,InportError,IndexErrorなど)

Sponsored Links

皆さんこんにちは
お元気ですか。プレゼン資料作るのって結構めんどくさいですね。

さて、本日はエラーについて
Pythonにも様々なエラーがありますがだいたいは決まっています。

そんなエラーの原因をご紹介します。

ImportError: No module named

そんなモジュールありません(今回はインポートでやってみました)

>>> import ssa
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named ssa

list index out of range

リストの参照先が範囲外です。

>>> list = []
>>> list[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: list index out of range

takes exactly (x) arguments ((?) given)

指定された関数と引数の数が異なります。
x = 必要な引数の数
? = 与えた引数の数

>>> def sum(a,b):
...  return a + b
... 
>>> sum(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() takes exactly 2 arguments (1 given)

NameError: name 'a' is not defined

aという変数は定義されていません

>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

実はこのエラーよくクラス作って書く時にselfの書き損じでやらかすことが多々…。

ValueError: invalid literal for int() with base 10

文字列を無理やりintに変換した場合

>>> print '%s' % int('amen')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'amen'

SyntaxError: invalid syntax

シンタックスエラー

>>> if aaa
  File "<stdin>", line 1
    if aaa
         ^
SyntaxError: invalid syntax

AttributeError: Temp instance has no attribute

インスタンスはその属性を持っていないよ

>>> class Temp:
...   def __init__(self):
...       a = 0
... 
>>> a = Temp()
>>> a.b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Temp instance has no attribute 'b'

AttributeError: class Temp has no attribute 'dcs'

クラスはその属性を保持していません

>>> b = Temp.dcs()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: class Temp has no attribute 'dcs'

unsupported operand type(s) for +

演算子がサポートされていません。

>>> sum(None,None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in sum
TypeError: unsupported operand type(s) for +: 'NoneType' and 'NoneType'

IndentationError: expected an indented block

インデントを下げましょう
>>> for 1 in xrange(10):
... 10
  File "<stdin>", line 2
    10
     ^
IndentationError: expected an indented block

TypeError: can only concatenate list (not "int") to list

list objectとintは連結ができません。

>>> a = 10
>>> list = [2,2]
>>> list + a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate list (not "int") to list

KeyError

辞書に登録されていない内容を出そうとした時

>>> dict = {}
>>> dict["aaa"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'aaa'

多分こんなところ、またあれば書きます。