[개념] Chapter04-3 : 파이썬 반복문 while

Date:     Updated:

카테고리:

태그:

인프런 강의 프로그래밍 시작하기 : 파이썬 입문을 듣고 정리한 내용입니다✏️.

while문 실습

기본

while <expr>:
    <statement(s)>

예제1

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

#5
#4
#3
#2
#1

예제2

# 예제2
a = ['foo', 'bar', 'baz']

while a:
    print(a.pop())

#baz
#bar
#foo

if 중첩

예제3 (break, continue)

n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)
print('Loop Ended.')

#4
#3
#Loop Ended.

예제4

m = 5
while m > 0:
    m -= 1
    if m == 2:
        continue
    print(m)
print('Loop Ended.')

#4
#3
#1
#0
#Loop Ended.

예제5

i = 1

while i <= 10:
    print('i:', i)
    if i == 6:
        break
    i += 1

#i: 1
#i: 2
#i: 3
#i: 4
#i: 5
#i: 6

while-else 구문

예제6

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

else:
    print('else out.')

#9
#8
#7
#6
#5
#4
#3
#2
#1
#0

예제7

a = ['foo', 'bar', 'baz', 'qux']
s = 'kim'

i = 0

while i < len(a):
    if a[i] == s:
        break
    i += 1
else:
    print(s, 'not found in list.')

# kim not found in list.

예제8

a = ['foo', 'bar', 'baz']

while True:
    if not a:
        break
    print(a.pop())

#baz
#bar
#foo

맨 위로 이동하기

Python 카테고리 내 다른 글 보러가기

댓글남기기