파이썬/Basic

파이썬 match-case 문

코샵 2023. 4. 3. 10:11
반응형
파이썬 3.10부터 match-case문이 도입되었습니다. match-case문은 switch-case문과 유사한 기능을 합니다. 하지만 switch-case문과는 몇 가지 차이점이 있습니다.

1. 패턴 매칭

match-case문은 패턴 매칭을 지원합니다. 이는 일련의 조건문을 작성하는 대신 하나의 match문 안에서 여러 패턴을 정의하여 코드를 간결하게 작성할 수 있습니다.

예를 들어, 다음과 같은 리스트가 있다고 가정합니다.

fruits = ['apple', 'banana', 'orange']

이 리스트의 각 항목에 대해 다른 동작을 수행하려면 switch-case문을 다음과 같이 작성할 수 있습니다.

for fruit in fruits:
    switch(fruit):
        case 'apple':
            print('This is an apple')
            break
        case 'banana':
            print('This is a banana')
            break
        case 'orange':
            print('This is an orange')
            break

하지만 match-case문을 사용하면 다음과 같이 간단하게 작성할 수 있습니다.

for fruit in fruits:
    match fruit:
        case 'apple':
            print('This is an apple')
        case 'banana':
            print('This is a banana')
        case 'orange':
            print('This is an orange')


2. 유연한 패턴

match-case문은 switch-case문과 달리 패턴 매칭을 사용하여 더 유연하게 코드를 작성할 수 있습니다. 예를 들어, 다음과 같은 코드를 작성해보겠습니다.

def check_type(x):
    match x:
        case int:
            print('This is an integer')
        case str:
            print('This is a string')
        case list:
            print('This is a list')
        case _:
            print('Unknown type')

check_type(10)
check_type('hello')
check_type([1, 2, 3])
check_type(3.14)

위 코드에서는 입력된 값의 타입에 따라 다른 메시지를 출력합니다. match문에서 _(언더스코어)는 모든 값에 대해 일치하는 패턴입니다. 따라서 입력된 값이 int, str, list 중 어느 타입에도 해당하지 않는 경우, _ 패턴이 일치하게 되어 'Unknown type' 메시지가 출력됩니다.


3. 패턴 중첩

match-case문은 패턴을 중첩하여 사용할 수 있습니다. 이는 더욱 복잡한 패턴 매칭을 가능하게 합니다.

예를 들어, 다음과 같은 코드를 작성해보겠습니다.

def check_value(x):
    match x:
        case [1, 2, 3]:
            print('This is [1, 2, 3]')
        case [1, _, 3]:
            print('This is a list with 1 and 3')
        case [1, _, _]:
            print('This is a list with 1 and two more items')
        case _:
            print('Unknown value')

check_value([1, 2, 3])
check_value([1, 4, 3])
check_value([1, 2, 3, 4])
check_value('hello')

위 코드에서는 입력된 값이 어떤 패턴과 일치하는지에 따라 다른 메시지를 출력합니다. [1, 2, 3] 패턴과 일치하는 경우 'This is [1, 2, 3]' 메시지가 출력됩니다. [1, _, 3] 패턴과 일치하는 경우 'This is a list with 1 and 3' 메시지가 출력됩니다. [1, _, _] 패턴과 일치하는 경우 'This is a list with 1 and two more items' 메시지가 출력됩니다. 어떤 패턴에도 일치하지 않는 경우, _ 패턴이 일치하게 되어 'Unknown value' 메시지가 출력됩니다.


결론

이상으로 파이썬 match-case문과 switch-case문의 차이점에 대해 알아보았습니다. match-case문은 switch-case문과 유사한 기능을 하지만, 패턴 매칭, 유연한 패턴, 패턴 중첩 등의 장점이 있습니다.