[Python]Match-Case

KyeongHun Kim·2024년 1월 4일

Python 공부

목록 보기
1/1

Python Match-Case

python 3.10.3 버전에 추가된 Match-Case 구문에 대해 알아보자!

Switch 구문이란?

  • if문과 비슷한 기능을 하는 제어문의 한 종류로 대부분의 언어에서 사용하고 있음.
  • if문 보다 가독성이 뛰어나고 컴파일링 최적화가 뛰어나다는 장점이 있음.
  • Python에는 Switch 구문 대신 if-elif문이나 dictionary형태로 사용하기를 권장하였으나 3.10.3 버전에서 Match-Case 구문을 추가하였음.

if-elif를 사용한 예시

정해진 학점에 따라 계산을 진행을 한다고 가정하자. 각 학점은 다음과 같다.

학점점수
A+4.5
A04.0
B+3.5
B03.0
grade = ['A+', 'B+', 'A0']
score_list = []
for score in grade: # 반복문을 돌면서 점수를 반환함.
	if score == 'A+':
    	score_list.append(4.5)
    elif score == 'A0':
    	score_list.append(4.0)
    elif score == 'B+':
    	score_list.append(3.5)
    elif score == 'B0':
    	score_list.append(3.0)
print(score_list)

dictionary를 사용한 예시

score_dict = {'A+' : 4.5, 'A0' : 4.0,
              'B+' : 3.5, 'B0' : 3.0}
grade = ['A+', 'B+', 'A0']
score_list = []
for score in grade: # key-value를 통해 score 값 할당
	score_list.append(score_dict[score])
print(score_list)

Match-case를 사용한 예시

grade = ['A+', 'B+', 'A0']
score_list = []
for score in grade:
    match score:
        case 'A+': score_list.append(4.5)
        case 'A0': score_list.append(4.0)
        case 'B+': score_list.append(3.5)
        case 'B0': score_list.append(3.0)
print(score_list)

Python Match-Case의 특징

Guard

guard ::= "if" named_expression의 형태로 표현되는 Guard는 '반드시' match되어야 하는 조건이다. case에 해당한다고 하더라도 Guard의 조건이 맞지 않으면 case는 선택되지 않고 다음 case로 넘어간다.

# 예시
flag = False
match (100, 200):
    case (100, 300):
        print('Case 1')
    case (100, 200) if flag: # case에는 해당하지만 Guard에 해당하지 않음.
        print('Case 2')
    case (100, y):  # Matches and binds y to 200
        print(f'Case 3, y: {y}')
    case _:  # Pattern not attempted
        print('Case 4, I match anything!')

Case 3, y: 200

Wild Card

wildcard_pattern ::= '_'의 형태로 표현되는 Wild Card는 항상 match되는 경우를 말한다.

# 예시
flag = False
match (100, 200):
    case (100, 300):
        print('Case 1')
    case (100, 400):
        print('Case 3)
    case _:  # Wild Card에 해당함.
        print('Case 4, I match anything!')
        
'Case 4, I match anything!'
profile
기본에 충실하자!

0개의 댓글