반응형

Python 3.10에서 추가된 C/C++의 switch case와 유사한 match case 예제입니다.



2022. 11. 4  최초작성



match문에 있는 변수 input의 값이  case 문에 있는 조건을 만족하면 해당 코드가 실행됩니다.  case 문에 값이 지정되지 않은 경우는 _를 사용한 case 문에 있는 코드가 실행됩니다. 

def f(input):

    match input:

        case 'apple':
            print('사과')
       
        case 'banana':
            print('바나나')

        case _:
            print('선택된 것이 없습니다.')


f('apple')
f('orange')

 

사과
선택된 것이 없습니다.



| 를 사용하여 두가지 이상의 조건을 하나의 case 문에 추가할 수 있습니다. 다음 예제에서는 input이 401 또는 403일 경우를 하나로 묶어주고 있습니다. 

def f(input):

    match input:
        case 400:
            print("Bad request")
        case 401 | 403:
            print("Authentication error")
        case 404:
            print("Not found")
        case _:
            print("Other error")


f(400)
f(401)
f(403)
f(500)

 

Bad request
Authentication error
Authentication error
Other error



case문에 두개 이상의 값이 주어지는 경우 예제입니다.

def alarm(item):
    match item:

        # 두개의 값이 주어진 경우입니다.
        case [time, action]:
            print(f'Good {time}! It is time to {action}!')

        # 두개 이상의 값이 주어진 경우 첫번째 값은 변수 time에 대입되고 나머지는 가변인자 actions에 대입됩니다. 
        case [time, *actions]:
            print('Good morning! ', end='')

            # 가변인자의 값을 하나씩 가져와 출력해줍니다.
            for action in actions:
                print(f'It is time to {action}! ', end='')


# 리스트에 값을 대입하여 alarm 함수를 호출합니다.
alarm(['afternoon', 'work'])
alarm(('morning', 'have breakfast', 'brush teeth', 'work'))

 

Good afternoon! It is time to work!
Good morning! It is time to have breakfast! It is time to brush teeth! It is time to work!



주어진 값이 지정된 값중 하나인지 체크하는 예제입니다. 

def alarm(item):
    match item:
        # 두개의 값이 주어진 경우로 첫번째 값이 morning, afternoon, evening 중 하나인지 체크합니다. print문의 time 변수 자리에 값이 출력됩니다.
        case [('morning' | 'afternoon' | 'evening') as time, action]:
            print(f'Good {time}! It is time to {action}!')
        case _:
            print('The time is invalid.')


alarm(['afternoon', 'work'])
alarm(['morning', 'work'])



Good afternoon! It is time to work!
Good morning! It is time to work!



참고

https://towardsdatascience.com/the-match-case-in-python-3-10-is-not-that-simple-f65b350bb025 

 

반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts