Python Basic _ 4-3. 반복문(while)

WONY_yoon·2025년 10월 3일
post-thumbnail

Python while 문법 알아보기

# chapter04-3
# 파이썬 반복문
# while 실습

# while <expr>:
#       <statement(s)>

# 예제 1
n = 5
while n > 0:
    print(n)       # 5, 4, 3, 2, 1
    n = n - 1

print()

n = 5
while n > 0:
    n = n - 1
    print(n)       # 4, 3, 2, 1, 0

print()

# 예제 2
a = ['foo', 'bar', 'baz']
while a:
    print(a.pop())  # baz, bar, foo

print()

# 예제 3
# break, continue
n = 5
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)       # 4, 3
print('Loop Ended.')   # Loop Ended.

print()

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

print()

# 예제 5
# if 중첩
i = 1
while i <= 10:
    print('i:', i)   # i: 1 ... i: 6
    if i == 6:
        break
    i += 1

print()

# 예제 6
# while - else
n = 10
while n > 0:
    n -= 1
    print(n)       # 9, 8, 7, 6, 5
    if n == 5:
        break
else:
    print('else out')   # 실행되지 않음 (break 때문에)

print()

# 예제 7
a = ['foo', 'bar', 'baz', 'qux']
s = 'qux'

i = 0
while i < len(a):
    if a[i] == s:
        break
    i += 1
else:
    print(s, 'not found in list.')   # 실행되지 않음 (break로 종료)

print()

# 무한반복
# while True:
#     print('Foo")

# 예제 8
a = ['foo', 'bar', 'baz']
while True:
    if not a:
        break
    print(a.pop())   # baz, bar, foo

0개의 댓글