Python의 경우, loop structure로 while statement와 for statement를 제공한다.
Contol Flow와 Control Structure에 대한 개념은 다음 URL을 참고 :
2025.04.23 - [Python] - [Programming] Control Flow 와 Control Structure
[Programming] Control Flow 와 Control Structure
Abstraction(추상화)을 통한 이해프로그래밍 언어에서 Abstraction은 복잡한 세부 사항을 숨기고 핵심 개념만 드러내는 프로그래밍의 기본 원칙임. Control Flow와 Control Structure는 프로그램의 Execution Path
ds31x.tistory.com
참고로 do-while statement 는 while statement 만으로도 구현가능하기 때문에 Python에선 지원하지 않음.
for statement가 iterable object와 함께 사용되는 것과 달리,
while statement는 if statement와 매우 유사한 구조로 repetition을 가능하게 함.

일반적인 구조.
while condition:
while_block
whilestatement는whilekeyword로 시작하고, 뒤에 놓이는conditionexpression이True로 reduction되는 경우엔while_block이 수행된다.while_block이 수행되고 나서 다시conditionexpression이 evaluation되고 그 결괏값이True이면 다시while_block이 수행된다.- 이는
conditionexpression이 계속True인 경우 계속해서 반복이 이루어짐. - 만약
conditionexpression이False인 경우엔while_block이 수행되지 않고whilestatement가 끝나게 된다.
condition 이란
True/False로 evaluate되는 expression을 가리킴.
위의 설명에서 알 수 있듯이, condition expression이 True가 유지되는 한 계속 반복이 이루어지나,
처음부터 False인 경우엔 아예 수행이 안된다.
예제0
다음은 while statement의 간단한 예이다.
4번 반복이 되어 1부터 4까지 integer가 출력된다.
a = 1
while a <5:
print(a)
a += 1
- while statement의 code block에서 마지막 line에 있는 augmented assignment "a += 1" 이 주석 처리할 경우, 무한루프에 빠짐.
break를 이용하여 다른 언어의 do-while 구현하기.
다른 프로그래밍 언어에서 제공하는 do-while과 같이 맨 처음은 무조건 수행되고 이후 반복할지를 condition exression의 결괏값으로 정하려면, break keyword를 이용해야 한다.
break가 수행될 경우, 현재의 해당 break 문이 포함된 가장 안쪽의 for 또는 while statement의 반복실행을 탈출하여 해당 반복을 종료시킨다.
while statement의 code block에서 break가 호출되면 while statement를 종료시켜 해당 loop의 code block에서 나와서 다음 line의 statement를 수행하게 됨.
실제로
while statement나 for statement와 같은 loop내에서만
break는 존재할 수 있음.
이 break와 if statement와 while statement를 다음과 같이 조합하면 do-while 과 같이 동작가능해진다.
while True: # condition expression이 True literal이 되면, 무한루프임.
# while_block_start
...
if not condition:
break
# while_block_end
conditionexpression이whilecode block의 끝에 놓인ifstatement에 위치함.- 만약
condition이 처음부터False였다고 해도while_block이 한번은 수행되고, 끝의ifstatement의 code block에 있는breakstatement에 의해whilestatement가 종료되게 된다. conditionexpression이True로 reduction된다면,whilestatement의 조건에 대한 evaluation이 이루어지고,Trueliteral로 고정된 상태이므로 다시whilestatement의 code block이 수행되게 된다.
예제1
다음은 break를 사용한 while statement의 예이다.
매 반복마다 종료여부를 물어보고 y가 입력되면 종료된다.
cnt = 0
while True:
cnt += 1
print('iteration #:',cnt)
ans = input('Do you want ot quit?[y/n]: ').strip().lower()
if ans == 'y':
break
print('done!')
continue statement
break와 함께 loop를 제어하는 statement가 continue이다.
continue 역시 loop 문 내부에서만 호출 가능함.
수행될 때 즉시 자신을 둘러싸고 있는 가장 안쪽의 repetition loop를 종료시키는 break statement와 달리
continue statement는
- 자신을 둘러싸고 있는 가장 안쪽의 repetition loop 의 현재 block의 나머지 부분을 수행하지 않고
- repetition의 다음 반복을 수행하게 된다.
while statement의 예를 든다면,
continue가 호출될 경우- 해당 line 아래에 위치한
whilestatement의 code들의 수행을 생략하고 whilestatement의 첫번째 line의conditionexpression을 evaluation하게 된다.
예제2
다음은 continue의 활용 예제로, string s에서 alphabet이 몇개인지를 count하는 while statement임.
s = 'a1b2b3c3'
cnt = 0
idx = 0
while True:
if idx >= len(s):
break
if not s[idx].isalpha():
idx += 1
continue
idx +=1
cnt += 1
print ('# of alphabets:', cnt)
- string은 immutable sequence type이며 iterable임을 잊지 말것.
더 읽어보면 좋은 자료
https://gist.github.com/dsaint31x/5297428fc4b701393d94f4348d89a0f9
py_while_break_continue.ipynb
py_while_break_continue.ipynb. GitHub Gist: instantly share code, notes, and snippets.
gist.github.com
2023.10.06 - [Pages] - [Python] Control Structure and Control Flow
[Python] Control Structure and Control Flow
Control structure와 Control Flow란 무엇인가?2025.04.23 - [Python] - [Programming] Control Flow 와 Control Structure [Programming] Control Flow 와 Control StructureAbstraction(추상화)을 통한 이해프로그래밍 언어에서 Abstraction은
ds31x.tistory.com
'Python' 카테고리의 다른 글
| [Python] PEP 8 : Style Guide for Python Code (0) | 2023.08.04 |
|---|---|
| [Python] asterisk * 사용하기 : unpacking, packing (1) | 2023.07.30 |
| [Python] if, elif, else statements (0) | 2023.07.28 |
| [Python] Boolean Operators, Relational Operators, Membership Operators and Identity Operator (0) | 2023.07.28 |
| [Python] List's methods (0) | 2023.07.17 |