기술(Tech, IT)/파이썬(Python)

[Python] pass vs continue vs break

Daniel803 2022. 9. 8. 02:21

파이썬 알고리즘 문제를 풀던 중 이중 반복문을 탈출하는 방법을 구글링하다 error를 발생시켜 탈출하는 방법을 알게 됐고, 예시에서 pass를 알게 됐다. 다음은 해당 예시다.

class LoopBreak(Exception):
    pass

try:
    for i in range(5):
        for j in range(5):
            if i == 1 and j == 1:
                raise LoopBreak()
except LoopBreak:
    pass

W3Schools에 따르면 pass의 정의는 다음과 같다.

 

pass

: The pass statement is used as a placeholder for future code. When the pass statement is executed, nothing happens, but you avoid getting an error when empty code is not allowed. Empty code is not allowed in loops, function definitions, class definitions, or in if statements.

: pass문은 향후 작성될 코드를 위해 선언한다. pass이 실행되면 아무일도 발생하지 않지만 비어있는 코드가 허용되지 않는 곳에서 error를 피할 수 있다. 반복문, 함수의 정의, 클래스의 정의, if문에는 코드가 비어있는 것이 허용되지 않는다.

 

이해를 돕기 위해 비슷한 기능을 하는 continue와 실행 결과를 비교해보자.

1. pass

i = 0
while i < 5:
    i = i + 1
    if i % 2 == 0:
        pass
    print(i)

실행 결과:

1

2

3

4

5

 

2. continue

: continue 문이 실행되면 현재 loop내에 작성된 continue 이후의 코드가 실행되지 않고 지나간다.

i = 0
while i < 5:
    i = i + 1
    if i % 2 == 0:
        continue
    print(i)

실행 결과:

1

3

5

 

3. break

: break 문이 실행되면 현재 실행되고 있는 loop를 즉시 탈출한다. 현재 loop만을 탈출하므로 다중 반복문일 경우 완전한 탈출은 할 수 없다.

i = 0
while i < 5:
    i = i + 1
    if i % 2 == 0:
        break
    print(i)

실행 결과:

1

 

출처:

1. https://chancoding.tistory.com/7

 

[Python] pass, continue, break 차이점 알아보기

pass continue break 차이점 Python 기본 문법에 있어 pass, continue break의 차이점을 알아보겠습니다. 1.    pass : 실행할 코드가 없는 것으로 다음 행동을 계속해서 진행합니다. 2.    continue : 바..

chancoding.tistory.com

2. https://www.w3schools.com/python/ref_keyword_pass.asp

'기술(Tech, IT) > 파이썬(Python)' 카테고리의 다른 글

[Python] subscriptable: TypeError  (0) 2022.09.28
[Python] 주석(Annotation)  (0) 2022.09.26
[Python] deque(데크)  (0) 2022.09.25
[Python] for문(for loop)  (0) 2022.09.10
[Python] 다중 반복문(multiple loops) 탈출  (0) 2022.09.09