Pythonは他の多くのプログラミング言語とは異なり、Switch文またはCase文を持っていません。しかし、Pythonでは代替手段として辞書やif-elif-else文を使用することができます。
if-elif-elseを使う方法
Switch文に代わる方法として、if-elif-else文があります。その構文と具体例をご覧ください。
x = 1
if x == 1:
print("x is 1")
elif x == 2:
print("x is 2")
else:
print("x is neither 1 nor 2")
ただし条件が多い場合、if-elif-else文が長くなり、可読性が低下することがあるため注意が必要です。
辞書を使う方法
if-elif-else文以外にも辞書を使う方法があります。少しトリッキーなやり方なので、詳しく見ていきましょう。
def case_1():
return "This is case 1"
def case_2():
return "This is case 2"
switch_dict = {
1: case_1,
2: case_2
}
x = 1
print(switch_dict.get(x, lambda: "Invalid case")())
辞書を使用したSwitch文の代替は、特に大量の条件分岐が存在する場合に有効です。コードの可読性を保てます。
Python 3.10以降で利用可能なmatch文
Python 3.10では、新たな制御文であるmatch文が導入されました。これは、他言語のSwitch文に似た機能を提供するものです。
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!")
以上がPythonでのSwitch文の代替手段についての解説です。Pythonの設計哲学は、明確で読みやすいコードを重視するため、Switch文が不要とされたのです。しかし、多くの条件を持つプログラムではSwitch文が便利であるため、PythonでもSwitch文の代替手段を模索する必要があります。