1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonのmatch文で他言語のswitch文のような条件分岐を書く

Posted at

はじめに

本記事はPythonでif … elif文を書いていて、他言語のswitch文ような構文が使えないか気になったので調べてみた備忘録になります。

環境

Python 3.12

match文の活用

Pythonのバージョン3.10で追加されたmatch文を活用できそうです。
参考:https://docs.python.org/ja/3.10/reference/compound_stmts.html#the-match-statement

簡単なif … elifの条件分岐を書いてみます。

index.py
def get_day(day_number):
    if day_number == 1:
        return "月曜日"
    elif day_number == 2:
        print("火曜日")
        return "火曜日"
    elif day_number == 3:
        return "水曜日"
    else:
        return "不正な値です"

get_day(2) # "火曜日"

上記のようなif … elif …条件分岐をmatch文では次のように書けそうです。

index.py
def get_day(day_number):
    match day_number:
        case 1:
            return "月曜日"
        case 2:
            print("火曜日")
            return "火曜日"
        case 3:
            return "水曜日"
        case _:
            return "不正な値です"

get_day(2) # "火曜日"

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?