Python에서 for 루프 중지
Najwa Riyaz
2023년10월10일
Python
Python Loop

이 기사에서는 Python에서 for
루프를 중지하는 다양한 방법을 소개합니다.
break
문을 사용하여 Python for
루프 중지
Python에서 for
루프를 중지하려면 break
문을 사용하십시오.
예를 들어,
max = 4
counter = 0
for a in range(max):
if counter == 3:
print("counter value=3. Stop the for loop")
break
else:
print("counter value<3. Continue the for loop. Counter value=", counter)
counter = counter + 1
continue
break
출력:
counter value<3. Continue the for loop. Counter value= 0
counter value<3. Continue the for loop. Counter value= 1
counter value<3. Continue the for loop. Counter value= 2
counter value=3. Stop the for loop
여기에서 for
루프 조건이 충족되는 한 다음과 같은 인쇄 문이 인쇄됩니다. 예를 들어 -
counter value<3. Continue the for loop. Counter value= 0
그러나 counter
값이 3
과 같으면 for 루프에서 벗어납니다. 따라서 for
루프가 중지됩니다.
코드를 함수로 래핑한 다음 return
문 사용
코드를 함수로 래핑한 다음 return
문을 사용합니다.
예를 들어,
def fncreturn():
return
max = 4
counter = 0
for a in range(max):
if counter == 3:
print("counter value=3. Stop the for loop")
fncreturn()
else:
print("counter value<3. Continue the for loop. Counter value=", counter)
counter = counter + 1
continue
break
출력:
counter value<3. Continue the for loop. Counter value= 0
counter value<3. Continue the for loop. Counter value= 1
counter value<3. Continue the for loop. Counter value= 2
counter value=3. Stop the for loop
여기서 카운터 값이 3
에 도달하면 함수가 호출됩니다. 함수에는 return
문이 있습니다. 그것을 게시하면 for 루프를 종료하는 데 도움이 됩니다.
Python for
루프를 중지하는 예외 발생
for
루프를 중지하려면 예외를 발생시킵니다.
예를 들어,
max = 4
counter = 0
try:
for a in range(max):
if counter == 3:
print("counter value=3. Stop the for loop")
raise StopIteration
else:
print("counter value<3. Continue the for loop. Counter value=", counter)
counter = counter + 1
except StopIteration:
pass
출력:
counter value<3. Continue the for loop. Counter value= 0
counter value<3. Continue the for loop. Counter value= 1
counter value<3. Continue the for loop. Counter value= 2
counter value=3. Stop the for loop
여기서 카운터 값이 3
에 도달하면 예외가 발생합니다. 즉시 for
루프에서 종료됩니다.
튜토리얼이 마음에 드시나요? DelftStack을 구독하세요 YouTube에서 저희가 더 많은 고품질 비디오 가이드를 제작할 수 있도록 지원해주세요. 구독하다