Python 조건문과 반복문, 순회 기법详解

본 문서에서는 Python의 조건문과 반복문에 대해 상세히 다룬다. 각 구문의 특성과 활용 상황, 그리고 다양한 순회 방법을 설명한다.

1. 조건문

1.1 기본 if-else 구조

Python의 조건문은 다른 프로그래밍 언어와 유사한 구조를 가지며, 복잡한 조건 판별에 유용하게 사용된다.

if 조건식1:
    실행문1
elif 조건식2:
    실행문2
elif 조건식3:
    실행문3
else:
    실행문4

1.2 중첩 if 문

조건문 내에 다시 조건문을 중첩하여 사용할 수 있다.

if 조건식A:
    if 조건식B:
        실행문A
    elif 조건식C:
        실행문B
    else:
        실행문C
elif 조건식D:
    실행문D
else:
    실행문E

1.3 match-case 패턴 매칭

Python 3.10 이상에서 도입된 match-case 문은 복잡한 데이터 구조를 처리할 때 특히 유용하다. 리스트, 딕셔너리, 튜플 등의 구조를 간단하게 매칭할 수 있다.

match 대상값:
    case 패턴1:
        동작1
    case 패턴2:
        동작2
    case 패턴3:
        동작3
    case _:
        기본동작

def http_status(code):
    match code:
        case 400:
            return "Bad Request"
        case 404:
            return "Not Found"
        case 418 | 429 | 503:
            return "Service Unavailable"
        case _:
            return "Unknown Error"

result = http_status(400)
print(result)

리스트 패턴 매칭

def check_scores(scores):
    match scores:
        case [int(first), int(second)] if first > second:
            print(f"점수 {first}가 점수 {second}보다 큽니다.")
        case [int(first), int(second)]:
            print(f"점수 {first}와 {second}가 기록되었습니다.")
        case _:
            print("잘못된 점수 형식입니다.")

# 전통적인 if-elif 방식과 비교
def check_scores_traditional(scores):
    if isinstance(scores, list) and len(scores) == 2:
        val1, val2 = scores
        if isinstance(val1, int) and isinstance(val2, int):
            if val1 > val2:
                print(f"점수 {val1}가 점수 {val2}보다 큽니다.")
            else:
                print(f"점수 {val1}와 {val2}가 기록되었습니다.")
        else:
            print("잘못된 점수 형식입니다.")
    else:
        print("잘못된 점수 형식입니다.")

# 테스트
check_scores([90, 75])
check_scores([60, 85])
check_scores([80])
check_scores([80, '75'])

match-case를 사용하면 리스트의 구조를 직접 해체하고 조건을 검사할 수 있어 코드가 훨씬 간결해진다.

튜플 패턴 매칭

def verify_location(point):
    match point:
        case (float(x), float(y)):
            print(f"좌표 ({x}, {y})는 유효합니다.")
        case _:
            print("잘못된 좌표 형식입니다.")

verify_location((2.5, 3.8))

딕셔너리 패턴 매칭

def display_profile(info):
    match info:
        case {"username": str(name), "age": int(age)}:
            print(f"이름: {name}, 나이: {age}")
        case {"username": str(name)}:
            print(f"이름: {name}, 나이 미제공")
        case _:
            print("잘못된 프로필 형식입니다.")

display_profile({"username": "Alice", "age": 28})
display_profile({"username": "Bob"})

2. 반복문

2.1 while 반복문

while 조건식:
    실행문

2.2 while-else 반복문

while 루프가 정상적으로 종료되면 else 블록이 실행된다. break로 중단된 경우는 실행되지 않는다.

while 조건식:
    실행문1
else:
    실행문2

2.3 for 반복문

for 문은 이터러블 객체(리스트, 튜플, 문자열, 딕셔너리, 세트 등)를 순회하는 데 사용된다.

for 변수 in 이터러블객체:
    실행문
else:
    실행문

colors = ["Red", "Green", "Blue", "Yellow"]
for color in colors:
    print(color)

# range() 함수와 함께 사용
for num in range(0, 5):
    print(num)

2.4 for-else 반복문

반복문이 완전히 종료된 후 else 블록이 실행되지만, break로 인해 중단된 경우는 실행되지 않는다.

animals = ["Cat", "Dog", "Bird", "Fish"]
for animal in animals:
    if animal == "Bird":
        print("새를 찾았습니다!")
        break
    print(f"현재 동물: {animal}")
else:
    print("모든 동물을 순회했습니다.")
print("반복문 종료")

2.5 range() 함수

range()는 숫자 시퀀스를 생성하는 내장 함수이다.

# 0부터 4까지
for i in range(5):
    print(i)

# 2부터 7까지
for i in range(2, 8):
    print(i)

# 0부터 9까지 3씩 증가
for i in range(0, 10, 3):
    print(i)

3. 반복 제어문

3.1 break 문

반복문을 즉시 종료하고 탈출한다. 해당하는 else 블록은 실행되지 않는다.

counter = 10
while counter > 0:
    counter -= 1
    if counter == 4:
        break
    print(counter)
print('반복 종료')

3.2 continue 문

현재 반복의 나머지语句을 건너뛰고 다음 반복으로 진행한다.

counter = 5
while counter > 0:
    counter -= 1
    if counter == 2:
        continue
    print(counter)
print('반복 종료')

3.3 pass 문

pass는 아무런 동작을 하지 않는 빈 문이다. 문법적으로 문장이 필요하지만 실제 처리가 필요 없는 경우에 사용한다.

용도 1: 함수 임시 구현

def placeholder_function():
    pass

용도 2: 최소 구조의 클래스


class EmptyClass:
    pass

용도 3: 조건문의 임시 처리

is_active = False
if is_active:
    pass
else:
    print("비활성 상태")

용도 4: 반복문의 임시 구조

for i in range(5):
    pass

4. 타입 확인: isinstance()

4.1 함수 설명

isinstance(객체, 클래스정보)

객체가 특정 타입 또는 타입 튜플에 속하는지 확인한다.

4.2 활용 예시

def welcome(target):
    if isinstance(target, str):
        print(f"안녕하세요, {target}님!")
    elif isinstance(target, dict) and 'name' in target:
        print(f"안녕하세요, {target['name']}님!")
    else:
        print("인사할 수 없는 대상입니다.")

welcome("Charlie")
welcome({"name": "David"})
welcome(999)

5. 순회 기법

5.1 딕셔너리 순회

heroes = {'ataraxia': '명랑', 'voyager': '용감'}
for key, value in heroes.items():
    print(f"{key} {value}")

5.2 시퀀스 순회

인덱스와 값 함께 사용

moves = ['rock', 'paper', 'scissors']
for index, move in enumerate(moves):
    print(f"인덱스 {index}: {move}")

여러 시퀀스 동시에 순회

queries = ['이름', '직업', '좋아하는 색']
answers = ['knight', '성배', '빨강']

for q, a in zip(queries, answers):
    print(f"{q}은(는) {a}입니다.")

역순 순회

for num in reversed(range(1, 10, 2)):
    print(num)

정렬된 순회

fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'grape']
for fruit in sorted(set(fruits)):
    print(fruit)

태그: python conditional-statements loops iteration match-case

6월 14일 18:08에 게시됨