이 포스트는 개인적으로 공부한 내용을 정리한 글입니다.
자세한 내용은 아래 참고자료를 봐주시면 감사하겠습니다.
Match문은 파이썬 3.10버전에 도입되었습니다.
자바의 switch문과 비슷합니다.
사용방법은 간단합니다.
error_code = 401
match error_code:
case 400:
print("Bad request")
case 401 | 403: # 401 or 403
print("Unauthorized")
case 404:
print("Not Found")
case _: # default
print("????????")
자바의 switch문에서는 case에 논리 연산을 넣을 수 있지만 파이썬은 안되는것 같습니다.
파이썬 공식 doc에도 해당 예시는 없네요.
개인적으로 많이 사용하지 않을것 같습니다.
아래는 다른 사용 예시입니다.
def message_converter(messages):
match messages:
case ["contact"]:
print("need to contact someone")
case ["contact", to]:
print("need to contact", to)
case ["contact", *to]:
print("need to contact", end=" ")
print(to)
case _:
print("????????")
message_converter(["contact"])
message_converter(["contact", "girl friend"])
message_converter(["contact", "girl friend", "mother", "father", "sister"])
message_converter(["call", "girl friend", "mother", "father", "sister"])
# result
need to contact someone
need to contact girl friend
need to contact ['girl friend', 'mother', 'father', 'sister']
????????