0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

よくあるエラー8個

Posted at

Python よくあるエラー一覧

1. SyntaxError: invalid syntax

  • 構文の誤り(カンマ、括弧、コロンの欠落等)
# 誤
if True print("Hello")

# 正
if True: print("Hello")

2. NameError: name '変数名' is not defined

  • 未定義の変数/関数の使用
# 誤 
print(value)

# 正
value = 42
print(value)

3. TypeError: '型' object is not callable

  • 関数として呼び出せないオブジェクトの使用
# 誤 
list = [1, 2, 3]
list()

# 正
my_list = [1, 2, 3]  
print(my_list)

4. IndexError: list index out of range

  • リスト範囲外のインデックス参照
# 誤
arr = [1, 2, 3]
print(arr[3])

# 正
arr = [1, 2, 3]
if len(arr) > 3:
   print(arr[3])

5. KeyError: 'キー'

  • リスト範囲外のインデックス参照
# 誤
data = {"name": "Alice"}
print(data["age"])

# 正
data = {"name": "Alice"}
print(data.get("age", "Key not found"))

6.AttributeError: 'オブジェクト' object has no attribute '属性名'

  • 存在しない属性/メソッドの呼び出し
# 誤
str_value = "hello"
str_value.append("!")

# 正
str_value = "hello"
str_value += "!"

7. ValueError: invalid literal for int() with base 10

  • 不適切な型変換
# 誤
value = int("hello")

# 正
value = "42"
if value.isdigit():
   print(int(value))

8. ZeroDivisionError: division by zero

  • ゼロ除算
# 誤
result = 10 / 0

# 正
denominator = 0
if denominator != 0:
   result = 10 / denominator
else:
   print("Cannot divide by zero")
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?