Python 루프 제어: break, continue, pass 문 실전 예제로 마스터하기
루프는 리스트, 튜플, 문자열, 딕셔너리, 세트 같은 시퀀스 반복을 가능하게 하는 대부분 프로그래밍 언어의 중추입니다. Python에선 for와 while 두 루프 구조가 이 목적 수행. 루프는 조건이 거짓 될 때까지 계속되지만, break, continue, pass 문으로 흐름 변경 가능.
루프 제어 문이란?
break – 나타나는 루프 즉시 종료.
continue – 현재 반복 나머지 건너뛰고 다음 반복 시작.
pass – 아무 동작 안 함; 구문상 블록 필요할 때 인터프리터 만족시키는 플레이스홀더.
이 문들은 개발자에게 루프 실행 세밀한 제어권 줘 코드 더 효율적이고 가독성 높게 만듭니다.
break 문
break 문은 실행 중인 최내부 루프 종료. 중첩 루프에선 현재 루프만 영향, 외부 루프는 계속 실행돼 선택적 종료 가능.
break 작동 원리 (플로차트)
과정은 단순:
루프 진입.
루프 조건 평가.
break 만나면 루프 종료.
아니면 루프 본문 실행.
조건 재평가하고 실패까지 반복.
예제
for 루프 내 break
my_list = ['Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']
for name in my_list:
print(name)
if name == 'Guru':
print('Found the name Guru')
break
print('Loop is terminated')
출력:
Siya
Tiya
Guru
Found the name Guru
Loop is terminated
while 루프 내 break
my_list = ['Siya', 'Tiya', 'Guru', 'Daksh', 'Riya', 'Guru']
index = 0
while True:
print(my_list[index])
if my_list[index] == 'Guru':
print('Found the name Guru')
break
index += 1
print('After while-loop exit')
출력:
Siya
Tiya
Guru
Found name Guru
After while-loop exit
중첩 루프 내 break
for i in range(4):
for j in range(4):
if j == 2:
break
print("The number is", i, j)
출력:
The number is 0 0
The number is 0 1
The number is 1 0
The number is 1 1
The number is 2 0
The number is 2 1
The number is 3 0
The number is 3 1
continue 문
continue 키워드는 현재 반복 나머지 코드 건너뛰고 바로 다음 루프 사이클 진행.
continue 작동 원리 (플로차트)
예제
for 루프 내 continue
for i in range(10):
if i == 7:
continue
print("The Number is:", i)
출력:
The Number is: 0
The Number is: 1
The Number is: 2
The Number is: 3
The Number is: 4
The Number is: 5
The Number is: 6
The Number is: 8
The Number is: 9
while 루프 내 continue
i = 0
while i <= 10:
if i == 7:
i += 1
continue
print("The Number is:", i)
i += 1
출력:
The Number is: 0
The Number is: 1
The Number is: 2
The Number is: 3
The Number is: 4
The Number is: 5
The Number is: 6
The Number is: 8
The Number is: 9
The Number is: 10
중첩 루프 내 continue
for i in range(4):
for j in range(4):
if j == 2:
continue
print("The number is", i, j)
출력:
The number is 0 0
The number is 0 1
The number is 0 3
The number is 1 0
The number is 1 1
The number is 1 3
The number is 2 0
The number is 2 1
The number is 2 3
The number is 3 0
The number is 3 1
The number is 3 3
pass 문
pass 키워드는 구문상 문장 필요하지만 원하는 동작 없을 때 쓰는 no-op 플레이스홀더. 향후 구현할 빈 함수 본문, 클래스, 루프, 조건 블록에 흔히 사용.