파이썬은 지금까지 Switch Case 구문을 지원하지 않았는데 Python 3.10 버전부터 Match case라는 비슷한 기능을 제공하기 시작하였습니다. Switch case로 구현 가능한 패턴들을 Match case로 구현할 수 있습니다.
1. Python 3.10 이전에, 딕셔너리로 구현한 Switch Case
3.10 버전 이전에는 아래와 같이 딕셔너리로 Switch case와 비슷하게 구현할 수 있었습니다. 딕셔너리에 case들을 입력하고, get()
으로 매칭되는 결과를 가져올 수 있습니다.
def number_to_string(dayOfWeek):
switcher = {
0: "zero",
1: "one",
2: "two",
}
return switcher.get(dayOfWeek, "nothing")
print(number_to_string(0))
print(number_to_string(1))
print(number_to_string(2))
print(number_to_string(3))
print(number_to_string(4))
Output:
zero
one
two
nothing
nothing
2. Python 3.10에 도입된 Match case(Switch Case 비슷)
3.10 버전에서 match case라는 문법이 도입되었는데 다른 언어의 Switch case와 비슷합니다. 코드를 보시면 사용법도 비슷합니다. match로 전달된 인자와 일치하는 케이스 구문이 실행됩니다. 따라서, 3.10 버전 이상에서는 Switch case로 구현 가능한 패턴들을 Match case를 이용하여 구현할 수 있습니다.
def number_to_string(agrument):
match agrument:
case 0:
return "zero"
case 1:
return "one"
case 2:
return "two"
case default:
return "nothing"
print(number_to_string(0))
print(number_to_string(1))
print(number_to_string(2))
print(number_to_string(3))
print(number_to_string(4))
Output:
zero
one
two
nothing
nothing
3. Match case의 다른 예제 (1)
위의 예제와 비교할 때, default는 _
으로 사용할 수 있고, case 조건에 |
를 사용하여 OR를 표현할 수 있습니다.
def http_status(status):
match status:
case 400:
return "Bad request"
case 401 | 403:
return "Unauthorized"
case 404:
return "Not found"
case _:
return "Other error"
print(http_status(400))
print(http_status(401))
print(http_status(403))
print(http_status(999))
Output:
Bad request
Unauthorized
Unauthorized
Other error
4. Match case의 다른 예제 (2)
아래와 같이 리스트로 match case 구문을 사용할 수 있습니다. *names
처럼 고정되지 않은 개수의 인자들을 받아서 처리할 수 있습니다.
def greeting(message):
match message:
case ["hello"]:
print("Hello!")
case ["hello", name]:
print(f"Hello {name}!")
case ["hello", *names]:
for name in names:
print(f"Hello {name}!")
case _:
print("nothing")
greeting(["hello"])
greeting(["hello", "John"])
greeting(["hello", "John", "Doe", "MAC"])
Output:
Hello!
Hello John!
Hello John!
Hello Doe!
Hello MAC!
Loading script...
Related Posts
- Python 소수점 반올림, round() 예제
- Python - String isdigit(), 문자열이 숫자인지 확인
- Python 소수점 버림, 4가지 방법
- 파이썬 주석 처리, 단축키 소개
- Python - Text 파일 읽고 쓰는 방법 (read, write, append)
- Python - String Formatting의 다양한 방법 정리(%, Str formatting, f-stirng)
- Python - os.path.join(), 폴더와 파일명으로 Path 생성
- Python - 파일을 읽고 한 줄씩 리스트에 저장
- Python - 문자열에서 줄바꿈(\n) 제거, 3가지 방법
- Python - Switch Case 구현 방법 (Match Case)
- 우분투에 Python 3.10 설치하는 방법
- Python - 문자열에서 특정 문자 제거, 3가지 방법
- Python - 함수 정의 및 호출 방법
- Python - 딕셔너리 초기화, 4가지 방법
- Python - input() 함수로 데이터 입력 받기
- Python - Tuple 사용 방법
- Python - 딕셔너리 정리 및 예제
- Python - String startswith(), 어떤 문자열로 시작하는지 확인
- Python - 날짜에서 월 이름 가져오기(숫자 -> 영어 이름 변환)
- Python - 어떤 날짜가 몇 주차인지 확인
- Python - D-Day 계산, 몇일 남았는지 날짜 세기
- Python - 날짜가 무슨 요일인지 계산
- Python - 어떤 날짜가 주말인지, 평일인지 확인
- Python - XML 생성 및 파일 저장
- Python - 특정 월의 시작 날짜, 마지막 날짜 얻기
- Python - XML 파싱, 태그 또는 요소 별로 읽기
- Python 버전 확인 방법 (터미널, cmd 명령어)
- Python - Selenium에서 웹페이지의 제목 가져오는 방법
- Python - 디렉토리, 파일 사이즈 계산
- Python 버전 확인 방법 (스크립트 또는 Command line)
- Python - 함수에서 두개 이상의 값 리턴
- Python - CSV 파일 읽기, 쓰기
- Python - 코드 실행 시간 측정
- Python - 반복문으로 리스트 순회 방법 (+ Index 출력)
- Python - with로 파일 열고 닫기