問題一覧に戻る
上級高度な機能
問題105: match文

match文(Python 3.10以降)は、パターンマッチングを行う構文です。値の構造や内容に基づいて分岐処理を行えます。caseで各パターンを定義し、|で複数の値をマッチ、変数で値をキャプチャ、_でデフォルトケースを表現します。switch文より柔軟で強力な機能を提供します。

# match文
def describe_value(value):
value:
0:
return "Zero"
1 | 2 | 3:
return "Small positive"
[x, y]:
return f"List with two elements: {x}, {y}"
_:
return "Something else"

# match文を使用
print(describe_value(0))
print(describe_value(2))
print(describe_value([10, 20]))
print(describe_value("hello"))