break 및 continue 를 사용하여 루프 흐름 제어하기
Python 은 루프의 일반적인 흐름을 변경하기 위해 break와 continue라는 두 가지 구문 (statement) 을 제공합니다.
break 구문은 현재 속한 루프를 즉시 종료합니다. 실행은 루프 다음의 첫 번째 구문으로 계속됩니다.
예시를 살펴보겠습니다. break_example.py 파일을 열고 특정 조건이 충족될 때 루프를 중지하는 다음 코드를 추가합니다.
## Iterate through numbers from 0 to 9
for i in range(10):
## If i is 5, the 'if' condition becomes True
if i == 5:
print(f"Breaking loop at i = {i}")
## The break statement exits the loop immediately
break
print(i)
print("Loop finished.")
파일을 저장하고 실행합니다.
python break_example.py
출력은 다음과 같습니다.
0
1
2
3
4
Breaking loop at i = 5
Loop finished.
i가 5가 되었을 때 루프가 중지되었으며, 5부터 9까지의 숫자는 출력되지 않았습니다.
continue 구문은 현재 반복 (iteration) 의 나머지 부분을 건너뛰고 다음 반복으로 진행합니다.
continue를 사용하여 특정 숫자의 출력을 건너뛰는 방법을 살펴보겠습니다. continue_example.py 파일을 열고 다음 코드를 추가합니다.
## Initialize a counter
count = 0
## Loop while count is less than 10
while count < 10:
count += 1
## If count is 5, the 'if' condition becomes True
if count == 5:
print(f"Skipping iteration at count = {count}")
## The continue statement skips the rest of this iteration
continue
## This line is skipped when count is 5
print(count)
print("Loop finished.")
파일을 저장하고 실행합니다.
python continue_example.py
출력은 다음과 같습니다.
1
2
3
4
Skipping iteration at count = 5
6
7
8
9
10
Loop finished.
이 경우, count가 5일 때 continue 구문이 실행되었습니다. 이로 인해 해당 반복에서는 print(count) 줄이 건너뛰어졌고, 루프는 count가 6이 되는 다음 반복으로 넘어갔습니다.