[Python] Switch-Case 구현


파이썬 Switch-case 구문이란?

한마디 버전:

한국어 : 파이썬은 Switch-case가 없습니다. 파이썬에서는 딕셔너리 맵핑으로 Switch-Case를 구현할 수 있으며, 더 좋은 가독성을 확보합니다.

영어 : Python doesn't have a switch-case statement. We implement a switch-case statement by using dictionary mapping with better readability.



1. 왜 없나? 있었는데 없어진건가? 원래 없었나?


처음부터 없었습니다.


누군가는 필요하다고 생각했습니다. 누군가는 다른 언어에 있는 기능을 넣고 싶기도 했을겁니다. 몇번 제안이 있긴 했지만, PEP 3103, PEP 275에서 파이썬팀에 의해 거절 되었습니다. 이유는 한가지 입니다. 원하는 사람이 많지 않기 때문이죠.

다른 언어에서는 데이터 값을 함수로 맵핑 해줄 만한 마땅한 구조체가 없기때문에 switch/case 구문이 있고, 파이썬은 딕셔너리 데이터 타입을 사용하여 구현할 수 있습니다.


물론 딕셔너리를 사용하지 않고 if...else 구문이나 class를 사용하는 등 다른 방법으로도 구현할 수 있지만, 어떤 방법을 고안해 내어도 파이썬 딕셔너리를 사용한 것보다 빠를 수 없을 것으로 예상됩니다.(예상입니다^^;)





2. 예제

Switch/Case 구문 (C++)

#include<bits/stdc++.h>
using namespace std;

// Function to convert number into string
string numbers_to_strings(int argument){
switch(argument) {
case 0:
return "zero";
case 1:
return "one";
case 2:
return "two";
default:
return "nothing";
};
};

// Driver program
int main()
{
int argument = 0;
cout << numbers_to_strings(argument);
return 0;
}



파이썬에서는 아래와 같이 사용합니다.

def func(x):
return {
'one': 1,
'two': 2,
}.get(x, 5) # 기본값 5, 옵션중 없다면 5를 리턴함

print(func('one'))


def east(): return "East"
def west(): return "West"
def north(): return "North"
def south(): return "South"

# 함수 블록 맵핑
switch_case = {
1 : east,
2 : west,
3 : north,
4 : south
}
print(switch_case[2]()) >>> 1 >>> West


  • [[a.original_name]] ([[a.file_size | fileSizer]])
좋아요[[ postLike | likePlus ]]
공유
라이언

“Lead Python Engineer”

댓글 [[totalCommentCount]]
[[ comment.author__nick_name ]] [[ comment.datetime_updated | formatDate]] (수정됨)

[블라인드 처리된 글 입니다.]

답장
[[ sub.author__nick_name ]] [[ sub.datetime_created | formatDate ]] (수정됨)

취소
댓글을 남겨주세요.
'파이썬' 관련 최신 포스트
[[ post.title ]]
[[ post.datetime_published_from | DateOnly ]]