\

Pythonは現代のプログラミング言語であり、常に進化しています。その最新の機能の一つがMatch-Case文です。Python 3.10で導入されたこの機能は、ある式を値のリストと比較することを可能にします。

Match-Case文とは何か?

プログラマーとして、しばしば複数の値に対して式を評価する必要があります。現代のプログラミング言語は、これを行うためのswitch文を提供しています。以下に、擬似コードの構文でswitch文の見た目を示します。

switch expression # the expression has a certain value
case 1:           # we test the value
do something    # the program performs an action depending on the value
case 2:
do something
case 3:
do something
default:          # if none of the case statements is satisfied
do something    # the program performs a default action

上記のコードでは、expressionが各case節の値と比較されます。一致するcase節が見つかると、そのcase節内のコードが実行されます。expressionに対する一致するcase節がない場合、default節の下のコードが実行されます。

Python 3.10でのMatch-Case文の実装方法

Python 3.10では、複数の値をテストし、条件付きのアクションを実行するための簡単で効果的な方法、つまりMatch-Case文を提供しています。C++に精通している場合、それはswitch caseと同様に動作します。

# First, ask the player about their CPU
cpuModel = str.lower(input("Please enter your CPU model: "))

# The match statement evaluates the variable's value
match cpuModel:
case "celeron": # We test for different values and print different messages
print ("Forget about it and play Minesweeper instead...")
case "core i3":
print ("Good luck with that ;)")
case "core i5":
print ("Yeah, you should be fine.")
case "core i7":
print ("Have fun!")
case "core i9":
print ("Our team designed nice loading screens… Too bad you won't see them...")
case _: # the underscore character is used as a catch-all.
print ("Is that even a thing?")

上記のコードは、cpuModel変数のいくつかの可能な値をチェックします。ユーザーが入力するCPUモデルが私たちの予想したオプションと一致しない場合、最終的なcase文はエラーメッセージを出力します。

Match-Case文の代替手段

Python 3.10は2021年に段階的に展開されています。もしまだPythonの古いバージョンを使用していて、すぐに更新できない場合でも、以下のような代替手段があります。

def f(x):
return {
'a': 1,
'b': 2,
}[x]

このように、PythonのMatch-Case文は、プログラム内で複数の値を効率的にテストするための強力なツールです。Pythonのバージョンに関係なく、この機能を最大限に活用して、より効率的なコードを書くことができます。

投稿者 admin

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です