루프를 이용할 때는 대부분 루프를 반복할 횟수를 추적하기 위해 별도의 정숫값을 보관하는 게 일반적이다. 어떤 초깃값으로 시작해, 루프를 반복할 때마다 값을 1
씩 증가시키고, 루프를 더 반복하기 전에 사전에 결정한 최댓값이 넘는지 검사한다. [프로그램 1.3.2](tenhellos.py)
는 이와 같은 while
반복문의 전형적인 예를 보여준다. 이 코드에서 핵심은 i = i + 1
이다.
프로그램 1.3.2 처음 만들어본 루프 (tenhellos.py)
import stdio stdio.writeln('1st Hello') stdio.writeln('2nd Hello') stdio.writeln('3rd Hello') i= 4 while i <= 10: stdio.writeln(str(i) + 'th Hello') i = i + 1
i |
루프 제어 카운터 |
이 프로그램은 while
루프를 이용해 Hello
를 10
번 출력한다. 세 번째 Hello
를 출력한 후에는 줄 수에 나오는 숫자만 다르므로, 이 인덱스를 보관하기 위해 변수 i를 정의한다. i
를 4
로 초기화한 후 while
루프에 들어가 stdio.writeln()
함수에서 i
를 사용하고 루프를 한 번 반복할 때마다 값을 증가시킨다. 프로그램이 10th Hello
를 출력한 후에는 i
가 11
이 되어 루프가 종료된다.
% python3 tenhellos.py 1st Hello 2nd Hello 3rd Hello 4th Hello 5th Hello 6th Hello 7th Hello 8th Hello 9th Hello 10th Hello
▼ 표 1.3.2 while 루프 트레이스
i |
i <= 10 |
출력 |
4 |
True |
4th Hello |
5 |
True |
5th Hello |
6 |
True |
6th Hello |
7 |
True |
7th Hello |
8 |
True |
8th Hello |
9 |
True |
9th Hello |
10 |
True |
10th Hello |
11 |
False |
|