LoginSignup
135

More than 5 years have passed since last update.

posted at

updated at

pythonにswitchはないけれど

追記(2014/2/6)
* pythonのバージョンは 2.7.5を用いました。python 3.Xでは確認しておりません。
* リスト型より辞書やセットの方が高速だと勧めて頂きましたので、修正致しました。


僕はswitch文が好きです。プログラムの見通しが断然良くなりますし、頭が整理されます。しかし、pythonにはswitch文は存在しません。条件分岐にはif, elif などを使うのがメジャーで、例えば以下のようなswitch文がある場合、

# javaなどで用いられる一般的なswitch文
switch(str){
case 'a':
case 'b':
    print('a,b'); break;
case 'c': 
    print('c'); break;
}

pythonでは、if, elif を使って以下のようになります。

if str == 'a' or str == 'b':
    print('a,b')
elif str == 'c':
    print('c')

最初のif 文の中で、 str == を 2回書くのは面倒くさいです。特に、これが2個以上であったり、変数名が長かったりすると、if文が長くなり、プログラムの可読性が落ちます。そこで、

if str in {'a', 'b'}:
    print('a, b')
elif str == 'c':
    print('c')

とすると、見通しが良くなります。python の in が便利であることを再確認させられますね。

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
What you can do with signing up
135