한양과학기술고등학교

에듀테크 프로젝트 대시보드

조건문 (if · match)

if elif else ternary match-case

블록은 들여쓰기로 구분합니다(보통 스페이스 4칸). 소괄호·중괄호는 필요 없습니다.

1. if / elif / else

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

# 참/거짓 판정은 truthy 규칙
if items:                # len(items) > 0 대신
    ...
if name is None:         # None 비교는 is
    ...

2. 삼항 연산자

status = "성인" if age >= 19 else "미성년"

# 중첩 (과하면 가독성 저하)
sign = "+" if n > 0 else "-" if n < 0 else "0"

# 리스트 컴프리헨션과 결합
[x if x > 0 else 0 for x in nums]

3. 논리 조건 조합

if 0 <= x < 100 and y != 0:
    ...
if user.is_admin or user.id == owner_id:
    ...
if not (a and b):
    ...

# in 으로 여러 값 비교
if cmd in ("q", "quit", "exit"):
    ...

4. match-case (3.10+)

def handle(command):
    match command.split():
        case ["go", direction]:
            return f"{direction}로 이동"
        case ["drop", *items]:
            return f"버림: {items}"
        case ["quit" | "exit"]:            # OR 패턴
            return "종료"
        case _:                            # 기본값 (와일드카드)
            return "알 수 없음"

5. 구조 분해 매칭

match point:
    case (0, 0):
        print("원점")
    case (x, 0):
        print(f"x축 위 {x}")
    case (x, y) if x == y:                 # 가드 조건
        print("대각선")
    case {"type": "circle", "r": radius}:  # dict 패턴
        print(f"반지름 {radius}")
    case Point(x=px, y=py):                # 클래스 패턴
        print(px, py)
match 주의
  • case "foo": 는 리터럴 매칭이지만 case x: 는 무조건 캡처(바인딩)
  • 기존 상수와 비교하려면 case Color.RED: 처럼 점(.) 포함 이름이어야 함
  • 단순 분기는 그냥 if/elif 가 더 명확

6. 들여쓰기 규칙

블록 규칙
  • 같은 블록은 들여쓰기 폭이 정확히 일치해야 함
  • 탭과 스페이스 혼용 금지 → TabError / 미묘한 버그. PEP8 은 스페이스 4칸
  • 빈 블록에는 pass 를 넣어 자리 표시
"특별한 경우라도 규칙을 어길 만큼 특별하지는 않다"