Skip to main content

조건문

학습 목표

  • if/elif/else 구문으로 프로그램 흐름을 분기할 수 있다
  • 삼항 연산자(Ternary Operator)로 간결한 조건식을 작성할 수 있다
  • match-case(Python 3.10+) 구조적 패턴 매칭을 활용할 수 있다
  • Python의 진리값(Truthiness) 판단 규칙을 이해한다

왜 중요한가

조건문은 프로그램이 상황에 따라 다른 동작을 수행하게 하는 핵심 제어 구조입니다. ML/DL에서 조기 종료(Early Stopping), 학습률 스케줄링, 모델 분기 등 모든 의사결정 로직이 조건문으로 구현됩니다.

if / elif / else

# 기본 구조
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
else:
    grade = "F"

print(f"점수: {score}, 등급: {grade}")  # 점수: 85, 등급: B

진리값 판단 (Truthiness)

Python에서 모든 객체는 bool()로 평가할 수 있습니다.
# Falsy 값들 (False로 평가)
if not 0:        print("0은 Falsy")
if not 0.0:      print("0.0은 Falsy")
if not "":       print("빈 문자열은 Falsy")
if not []:       print("빈 리스트는 Falsy")
if not {}:       print("빈 딕셔너리는 Falsy")
if not set():    print("빈 집합은 Falsy")
if not None:     print("None은 Falsy")

# Truthy 활용 - Pythonic 조건문
data = [1, 2, 3]

# 비추천
if len(data) > 0:
    print("데이터 있음")

# 추천 (Pythonic)
if data:
    print("데이터 있음")

복합 조건

age = 25
has_license = True
is_sober = True

# and, or, not
if age >= 18 and has_license and is_sober:
    print("운전 가능")

# 괄호로 가독성 확보
if (age >= 18 and has_license) or is_emergency:
    print("허용")

# 체이닝
score = 85
if 80 <= score < 90:
    print("B등급")

# in 연산자
fruit = "사과"
if fruit in ["사과", "바나나", "체리"]:
    print(f"{fruit}는 목록에 있습니다")

삼항 연산자

# 기본 형태: 참_값 if 조건 else 거짓_값
age = 20
status = "성인" if age >= 18 else "미성년"
print(status)  # "성인"

# 중첩 (가독성 주의)
score = 85
grade = "A" if score >= 90 else "B" if score >= 80 else "C" if score >= 70 else "F"

# 함수 호출에서 활용
print("합격" if score >= 60 else "불합격")

# 리스트 컴프리헨션과 조합
numbers = [1, -2, 3, -4, 5]
absolute = [x if x >= 0 else -x for x in numbers]
print(absolute)  # [1, 2, 3, 4, 5]

match-case (Python 3.10+)

구조적 패턴 매칭(Structural Pattern Matching)은 값의 구조를 기반으로 분기합니다.
# 기본 패턴
def http_status(code):
    match code:
        case 200:
            return "OK"
        case 301:
            return "Moved Permanently"
        case 404:
            return "Not Found"
        case 500:
            return "Internal Server Error"
        case _:    # 와일드카드 (default)
            return f"Unknown: {code}"

print(http_status(200))  # "OK"
print(http_status(418))  # "Unknown: 418"

# OR 패턴
match code:
    case 200 | 201 | 204:
        return "Success"
    case 400 | 401 | 403 | 404:
        return "Client Error"

# 구조 분해 패턴
point = (3, 4)
match point:
    case (0, 0):
        print("원점")
    case (x, 0):
        print(f"X축 위: x={x}")
    case (0, y):
        print(f"Y축 위: y={y}")
    case (x, y):
        print(f"좌표: ({x}, {y})")

# Guard 조건
match score:
    case n if n >= 90:
        grade = "A"
    case n if n >= 80:
        grade = "B"
    case _:
        grade = "C 이하"

딕셔너리 패턴 매칭

# API 응답 처리
response = {"status": "success", "data": {"name": "test", "value": 42}}

match response:
    case {"status": "success", "data": {"value": int(v)}}:
        print(f"성공: 값={v}")
    case {"status": "error", "message": msg}:
        print(f"에러: {msg}")
    case _:
        print("알 수 없는 응답")

AI/ML에서의 활용

# 조기 종료 (Early Stopping)
patience = 5
best_loss = float("inf")
wait = 0

for epoch in range(100):
    val_loss = train_one_epoch()  # 가상의 학습 함수

    if val_loss < best_loss:
        best_loss = val_loss
        wait = 0
        # save_checkpoint(model)
    else:
        wait += 1
        if wait >= patience:
            print(f"Epoch {epoch}: 조기 종료")
            break

# 학습률 스케줄링
def get_learning_rate(epoch):
    if epoch < 10:
        return 1e-3        # 워밍업
    elif epoch < 50:
        return 1e-4        # 기본 학습
    else:
        return 1e-5        # 미세 조정

# 모델 선택 분기
match model_type:
    case "bert":
        model = load_bert()
    case "gpt":
        model = load_gpt()
    case "t5":
        model = load_t5()
    case _:
        raise ValueError(f"지원하지 않는 모델: {model_type}")
match-case는 값뿐 아니라 데이터의 구조(튜플, 딕셔너리 등)를 분해하면서 매칭할 수 있습니다. 단순한 값 비교는 if-elif가 더 직관적이고, 구조 분해가 필요하면 match-case가 적합합니다.
Python 3.9까지는 switch-case가 없었습니다. 딕셔너리 디스패치 패턴이 대안으로 사용되었고, Python 3.10에서 match-case가 추가되었습니다.

체크리스트

  • if/elif/else로 다중 분기를 구현할 수 있다
  • Python의 Truthiness 규칙을 이해하고 Pythonic 조건문을 작성할 수 있다
  • 삼항 연산자를 적절히 활용할 수 있다
  • match-case로 구조적 패턴 매칭을 수행할 수 있다

다음 문서