본문 바로가기
Python

[Python] else: break checker

by ds31x 2023. 9. 18.
반복문에서 else
loop 가 break로 끝나지 않을 경우 수행되는 code block을 지정.
https://www.linkedin.com/posts/rodrigo-gir%C3%A3o-serr%C3%A3o_the-for-loop-in-python-can-be-followed-activity-7269835572683177984-xP7_/

조건문에서 else

일반적으로 else의 경우, 앞서의 ifelif문들에서 실행된 block이 없는 경우 수행되는 것을 의미한다.

2023.07.28 - [Python] - [Python] if, elif, else statements

 

[Python] if, elif, else statements

if, elif, else statements (조건분기문)프로그램의 flow control를 담당함. (loop문과 함께)Flow control을 위한 Control Structures에 대한 내용은 다음 URL을 참고.http://ds31x.blogspot.com/2023/07/basic-control-structures-and-contr

ds31x.tistory.com


반복문에서 else

그런데 python에서는 forwhile과 같은 loop structure 에서도
else를 뒤에 붙여서 break로 해당 loop가 나왔는지를 체크할 수 있다.

 

정확히 말하면, loop structure 에서의 else
앞서의 loop structure에서 break로 종료되지 않은 경우에 수행된다.

  • 하지만, 다른 언어에는 없는 방식의 응용인데다...
  • 앞서의 조건에 걸리지 않았을 때만 수행된다는 else조건분기에서 의미와도 잘 맞지 않기 때문에
    많은 책들이나 tutorial에서 사용을 권하지 않는다.
  • 가능하다고 해서 해도 된다는 건 아님

때문에 loop structure에서는 else단순히 break checker로 인식하되 많은 사용은 하지 않는 게 좋다.

 

다음 code snippet을 참고하자.

n = range(1,10,2)

idx = 0

for idx in n:

    if idx % 2 == 0:
        print(f'{idx} is an even number!')
        break
    else:
        print(f'{idx} is not an even number!')
else: # break checker
    print('There is not an even number!')    

idx = 1
while (idx := idx+2) < 10:
    if idx % 2 == 0:
        print(f'{idx} is an even number!')
        break
    else:
        print(f'{idx} is not an even number!')
else: # break checker
    print('There is not an even number!')

같이보면 좋은 자료들

2023.07.28 - [Python] - [Python] while statement, break and continue

 

[Python] while statement, break and continue

Python의 경우, loop structure로 while statement와 for statement를 제공한다. Contol Flow와 Control Structure에 대한 개념은 다음 URL을 참고 : http://ds31x.blogspot.com/2023/07/basic-control-structures-and-control.html 참고로 do-while

ds31x.tistory.com

https://dsaint31.tistory.com/573

 

[Python] for statement

for statement는 loop를 위한 control structure의 대표격이다.더보기https://ds31x.blogspot.com/2023/07/basic-control-structures-and-control.html Basic : Control Structures and Control FlowControl Structure 프로그램을 구성하는 statement

dsaint31.tistory.com

2023.10.06 - [Pages] - [Python] Control Structure and Control Flow

 

[Python] Control Structure and Control Flow

Control structure와 Control Flow란 무엇인가? http://ds31x.blogspot.com/2023/07/basic-control-structures-and-control.html Basic : Control Structures and Control Flow Control Structure 프로그램을 구성하는 statement (=excutable code)들이 실

ds31x.tistory.com