4.4. break, continue, else

breakand continueStatements, and elseClauses on Loops

breakcontinue문법, 그리고 반복문법(Loops)에서 사용되는 else


The break statement, like in C, breaks out of the smallest enclosing for or while loop.
break문법은 C에서와 마찬가지로 for또는 while반복문법에서 잠시 멈추는 것을 의미한다.

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:
Loop 문법은 else절을 가질 수 있다. else절은 Loop가 리스트(for문법 사용시)를 종료할 때 또는 조건이 맞지 않을 때(while 문법 사용시) 사용된다. 하지만 loop가 break 문법으로 종료되었을 때는 사용되지 않는다. 아래 예시는 소수를 검색하는 루프이다.

>>> for n in range(2, 10):
...     for x in range(2, n):
...         if n % x == 0:
...             print(n, 'equals', x, '*', n//x)
...             break
...     else:
...         # 루프가 인자를 찾지 못한 경우
...         print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

(Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if statement.)
(언뜻 이 코드는 잘못된 것처럼 보일 수도 있다. 하지만 breakif에, else절은 forloop에 속해있으므로 옳다.

When used with a loop, the else clause has more in common with the else clause of a try statement than it does that of if statements: a try statement’s else clause runs when no exception occurs, and a loop’s else clause runs when no break occurs. For more on the try statement and exceptions, see Handling Exceptions.
else절은 loop와 함께 사용될 때 if문법보다 try문법과 유사하다. try문법의 else 절은 예외가 발생하지 않았을 때 작동하며, loop의 else 절은 break가 실행되지 않았을 때 작동한다. try 문법에 대한 추가적인 내용과 예외는 Handling Exceptions 를 참고할 수 있다.
-Hnadling Exceptions 에 링크가 걸려있으나 아직 처리하지 못함
The continue statement, also borrowed from C, continues with the next iteration of the loop:
continue 문법 또한 C에서 착안한 것으로, loop의 다음 차례 반복에 이어진다.

>>> for num in range(2, 10):
...     if num % 2 == 0:
...         print("Found an even number", num)
...         continue
...     print("Found a number", num)
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9

results matching ""

    No results matching ""