본문 바로가기
C.W.K.
Stream
Lesson 03 of 07 · published

for와 while — 반복을 끝내는 여러 방법

~20 min · for, while, loop, else-on-loop

Level 0호기심
0 XP0/93 lessons0/23 achievements
0/100 XP to next level100 XP to go0% complete

for는 반복 가능한 값을 직접 걷는다

Python의 for는 인덱스를 세기보다 반복 가능한 객체에서 값을 하나씩 받아. 위치도 필요하면 enumerate, 여러 반복값을 나란히 묶으면 zip을 써. 길이가 다른 zip은 가장 짧은 쪽에서 끝나.

조건이 이어지는 동안에는 while

while은 다음 반복 여부가 어떤 조건에 달렸을 때 맞아. 읽은 값을 곧바로 검사해야 한다면 할당 표현식으로 중복 호출을 줄일 수 있지만, 한 줄에 너무 많은 일을 숨기지는 마.

continue, break, 그리고 else

continue는 이번 차례의 남은 부분을 건너뛰고, break는 반복 전체를 끝내. 반복의 elsebreak 없이 끝까지 갔을 때만 실행돼. 무언가를 찾으면 멈추고, 끝까지 못 찾았을 때 처리하는 모양에 잘 맞아.

걷는 길을 걷는 중에 허물지 마

리스트나 딕셔너리를 순회하면서 크기를 바꾸면 원소를 건너뛰거나 오류가 날 수 있어. 사본을 순회하거나 결과를 새 컨테이너에 모아.

Code

반복 가능한 값을 직접 걷는 for·python
fruits = ["apple", "banana", "cherry"]

# 값 순회
for f in fruits:
    print(f)

# 인덱스 같이 — range(len()) 쓰지 말고
for i, f in enumerate(fruits):
    print(i, f)

# 시작 인덱스 커스텀
for i, f in enumerate(fruits, start=1):
    print(i, f)
# 1 apple
# 2 banana
# 3 cherry
zip으로 여러 값 나란히 걷기·python
names = ["alice", "bob", "charlie"]
ages = [30, 25, 35]

for name, age in zip(names, ages):
    print(f"{name} is {age}")

# zip 은 가장 짧은 거에서 멈춤
tickers = ["AAPL", "MSFT", "GOOG", "NVDA"]
prices = [180, 420, 145]
for t, p in zip(tickers, prices):
    print(t, p)
# 3 페어만 출력 — NVDA 는 떨어짐

# zip(strict=True) 는 길이 다르면 raise — 3.10+
try:
    for t, p in zip(tickers, prices, strict=True):
        pass
except ValueError as e:
    print(e)
while에서 읽고 바로 검사하기·python
import io
# 파일인 척
f = io.StringIO("line1\nline2\nline3\n")

# 옛 어색한 스타일
# while True:
#     line = f.readline()
#     if not line:
#         break
#     process(line)

# 3.8+ walrus — 깔끔
while (line := f.readline()):
    print("got:", line.strip())
# got: line1
# got: line2
# got: line3
break가 없을 때만 실행되는 else·python
def find_negative(items):
    for i, x in enumerate(items):
        if x < 0:
            print(f"first negative at index {i}")
            break
    else:
        print("음수 없음")

find_negative([1, 2, 3])         # 음수 없음
find_negative([1, -2, 3])        # first negative at index 1

# else 는 while 에서도
n = 100
while n > 1:
    if n % 2 == 1:                # 홀수
        print("홀수 만남")
        break
    n //= 2
else:
    print("홀수 없이 끝까지 반")
# 홀수 없이 끝까지 반
순회 중 컨테이너를 바꾸지 않는 방법·python
items = [1, 2, 3, 4, 5, 6]

# 위험 — 이상한 동작, 원소 건너뛸 수 있음
# for x in items:
#     if x % 2 == 0:
#         items.remove(x)

# 안전 1 — 슬라이스 사본 순회
items = [1, 2, 3, 4, 5, 6]
for x in items[:]:
    if x % 2 == 0:
        items.remove(x)
print(items)              # [1, 3, 5]

# 안전 2 — 컴프리헨션으로 새 list
items = [1, 2, 3, 4, 5, 6]
items = [x for x in items if x % 2 != 0]
print(items)              # [1, 3, 5]

External links

Exercise

tickers = ['AAPL', 'MSFT', 'GOOG', 'NVDA'], prices = [180, 420, 145, 950]을 enumerate와 zip으로 출력해. 이어서 가격이 200 미만인 첫 티커를 찾아 break하고, 없다면 반복문의 else에서 'all expensive'를 출력해. 마지막에는 iter('pippa')while (ch := next(it, None)):로 글자를 하나씩 출력해.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.