Python 3.10から導入された新機能、match-case
文について解説します。この機能は、値に応じた処理の分岐を行うための構文で、条件分岐が厳密に定められることや、条件が入れ子になってしまった場合にもスッキリとまとまることが特徴です。
case文の基本的な使い方
以下に、基本的なcase
文の使い方を示します。
a:int = 2
match a:
case 1:
print("this is 1")
case 3:
print("this is 3")
case _:
print("Other") # Other
このコードでは、変数a
の値に応じて異なるメッセージを出力します。case 1:
とcase 3:
はそれぞれa
が1と3の場合に対応し、case _:
はそれ以外のすべての値に対応します。
case文と比較演算子
case
文は比較演算子と組み合わせて使用することも可能です。以下に、その例を示します。
sample = "hello"
match sample:
case int(x) if sample > 0:
print("sample is integer and greater than 0")
case str(x) if sample == "hello":
print("sample is string and 'hello'")
case int(x):
print("sample is integer")
case str(x):
print("sample is string")
case _:
print("other!") # sample is string and 'hello'
このコードでは、sample
の値と型に応じて異なるメッセージを出力します。case int(x) if sample > 0:
はsample
が整数で0より大きい場合に対応し、case str(x) if sample == "hello":
はsample
が文字列で”hello”と等しい場合に対応します。
以上がPythonのcase
文と比較演算子の基本的な使い方になります。これらの機能を活用することで、より柔軟な条件分岐を行うことが可能になります。