while 루프

매일 공부(ML)·2022년 2월 7일
0

학습목표

파이썬에서의 반복작업은 어떤식으로 수행되는지 이해하고 활용할 수 있다.


핵심 키워드

while 루프


While

*전문

while와 :(콜론) 사이에 오는 조건문이 참의 값을 가지는 경우에는 콜론 이하의 코드를 반복해서 작동을 합니다. 그러나 무한 루프에 빠질 수도 있는 단점도 있습니다.

n = 5

while n > 0:
    print(n)
    n = n - 1

print('Blastoff!')
print(n)

*break

루프가 break를 만나면 해당 루프의 실행이 종료 되어 while문 바로 뒤의 코드로 실행합니다.

while True:
    line = input('> ') 
    if line == 'done':
        break
    print(line)
print('Done!')

# > hello there로 입력
# hello there로 출력됨
# > finished로 입력
# finished로 출력됨
# > done로 입력
# Done!으로 출력됨

*continue

루프가 continue를 만나서 해당 루프는 실행이 종료되고 시작된 지점부터 다시 실행

while True:
    line = input('> ')
    if line[0] == '#' :
        continue
    if line == 'done' :
        break
    print(line)
print('Done!')

# > hello there 입력
# hello there로 출력
# # don't print this '#'을 입력하게 되면 continue를 만나게 되고 continue는 loop의 시작점으로 다시 돌아가서 loop를 실행하게 됩니다.
# > print this! 입력
# print this!로 출력
# > done 입력
# Done!으로 출력 done을 입력하게 되면 break를 만나게 되고 break는 loop끝나는 점 바로 다음에 오는 코드를 실행하게 됩니다.
profile
성장을 도울 아카이빙 블로그

0개의 댓글