개발자 모드/파이썬(python)

파이썬 python 의 while 문 반복문

인생은직구 2021. 6. 11. 22:34
728x90

# chapter 04-03
# 파이썬 반복문
# while 실습

# while <expr> :
#       statement(s)

# 예제1

n = 5

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

print()

# 예제2

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

while a:
    print(a.pop())

print()

# 예제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()


#  if 중첩

i = 1

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

print()


# while else 구문

n = 10

while n > 0 :
    n -= 1
    print(n)
#    if n ==5:
#        break
else:
    print('else out')

# 예제

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')


print()

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



# 예제

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

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

 

 

결과

 

[Command: python -u C:\python_basic\chapter04_03.py]
5
4
3
2
1

baz
bar
foo

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
4
3
2
1
0
else out

baz
bar
foo
[Finished in 0.143s]

 

728x90