Python Match-Case
python 3.10.3 버전에 추가된 Match-Case 구문에 대해 알아보자!
if-elif를 사용한 예시정해진 학점에 따라 계산을 진행을 한다고 가정하자. 각 학점은 다음과 같다.
| 학점 | 점수 |
|---|---|
| A+ | 4.5 |
| A0 | 4.0 |
| B+ | 3.5 |
| B0 | 3.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)
Guardguard ::= "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
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!'