Python の case/switch ステートメントに相当するものは何ですか? [重複] 質問する

Python の case/switch ステートメントに相当するものは何ですか? [重複] 質問する

switchこのステートメントに相当する Python はありますか?

ベストアンサー1

Python 3.10以上

Python 3.10 では、パターン マッチングが導入されました。

Pythonドキュメント:

def http_error(status):
    match status:
        case 400:
            return "Bad request"
        case 404:
            return "Not found"
        case 418:
            return "I'm a teapot"

        # If an exact match is not confirmed, this last case will be used if provided
        case _:
            return "Something's wrong with the internet"

Python 3.10以前

一方、公式文書提供しないことに満足しているswitch、私は見た辞書を使った解決法

例えば:

# define the function blocks
def zero():
    print "You typed zero.\n"

def sqr():
    print "n is a perfect square\n"

def even():
    print "n is an even number\n"

def prime():
    print "n is a prime number\n"

# map the inputs to the function blocks
options = {0 : zero,
           1 : sqr,
           4 : sqr,
           9 : sqr,
           2 : even,
           3 : prime,
           5 : prime,
           7 : prime,
}

次に同等のswitchブロックが呼び出されます。

options[num]()

フォールスルーに大きく依存すると、これは崩れ始めます。

おすすめ記事