[Python]While 반복문

파이썬의 While의 반복문에 대해 알아보자

# While 반복문
# while <expr>:
#     <statement(s)>

# 예1
n = 5
while n > 0:
    print("n = ", n)
    n = n - 1
print()

# 예2
a = ['foot', 'hands', 'bar', 'baz']
while a:
    print(a.pop())  # stack

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

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

# 예5 : if 중첩
i = 1
while i <= 10:
    print(f'i = {i}')
    if i == 6:
        break
    i += 1
print()

# 예6 : while ~ else 구문
n = 10
while n > 0:
    n -= 1
    print(n)
    if n == 5:
        break
else:  # 반복문이 중단없이(break 또는 continue) 수행될 경우 수행된다.
    print('else out.')
print()

# 예7
a = ['aa', 'bb', 'cc', 'dd']
s = 'dd'

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

# 예8 : 무한반복 주의
a = [1, 2, 3]
while True:
    if not a:
        break
    print("a.pop() =", a.pop())

결과:

n =  5
n =  4
n =  3
n =  2
n =  1

baz
bar
hands
foot
4
3
Loop Ended

4
3
1
0
Loop Ended

i = 1
i = 2
i = 3
i = 4
i = 5
i = 6

9
8
7
6
5

a.pop() = 3
a.pop() = 2
a.pop() = 1

You may also like...

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다