# [Python] 1. Match-Case

이원규·2023년 1월 7일
0

Python

목록 보기
1/2

Match-Case문

C++의 Switch-Case문과 비슷함.

match obj:
	case A:
    	A code ...
    case B:
    	B code ..
    case default:
    	default code

이런 식으로 obj가 A를 만족하면 A의 A code가 실행되고, B를 만족하면 B코드가 실행됨. 아무것도 만족하지 않을 시 default code가 실행됨.

예시 0) : 기본 사용 형태

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))

예시 1) :

def http_status(status):
    match status:
        case 400:
            return "Bad request"
        case 401 | 403:
            return "Unauthorized"
        case 404:
            return "Not found"
        case _: # default , or case default:
            return "Other error"

예시 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"])

예시 3) : tuple 형식에 대한 경우도 다음과 같이 처리할 수 있다.

for n in range(1, 101):
    match (n % 3, n % 5):
        case (0, 0):
            print("FizzBuzz")
        case (0, _):
            print("Fizz")
        case (_, 0):
            print("Buzz")
        case _:
            print(n)

참고 :

1. https://wikidocs.net/173398

2. https://codechacha.com/ko/python-switch-case/

profile
github: https://github.com/WKlee0607

0개의 댓글