반복문- while문

 

 

 

 

 

 

# 파이썬 반복문
While 실습

 

 


While 흐름 제어 실습

while 기본 사용법
Break,continue
while-Else 구문
무한 반복 구문
기본 패턴 실습



# while <expr>:          expr은 <expression>표현
#    <statement(s)>     statement(s)는 <code>
#조건을 만족할 동안 계속 반복하고 만족하지 않을 때 While문을 빠져나간다.

# 예제1
n = 5
while n > 0:
    print(n)
    n = n - 1 #이게 없으면 무한히 반복한다.

5
4
3
2
1
    

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

while a:          #0개가 되면 a가 false가 된다.
    print(a.pop())
    
baz
bar
foo



# if 중첩
# break , continue

 

# 예제3

n = 5
while n > 0:
    n -= 1 #n = 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: #else구문은 실행되지 않음.
    n -= 1
    print(n)
    if n == 5:
        break
else:
    print('else out.')
    
9
8
7
6
5



n2 = 10
while n2 > 0:
    n2 -= 1
    print(n2)
else:
    print('else out.')
    
9
8
7
6
5
4
3
2
1
0
else out.

#for문과 마찬가지로 정상적으로 모든 반복을 수행한다면 마지막에 else문을 딱 한번 실행하고 끝난다.
#else구문에 for문이나 while문에서 처리하고 마지막에 한 번 실행되야 하는 코드를 넣어주면
#깔끔하게 프로세스에 맞는 코딩을 흐름을 제어할 수 있다.




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

i = 0

while i < len(a): # i < 4 len길이
    if a[i] == s:
        break
    i += 1
else:
    print(s, 'not found in list.')
    
#출력값 없음

#찾았기 때문에 else구문이 실행되지 않음
#만약에 s = 'kim'이라고 하면 kim not found in list라고 나온다.

 

 




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

# 예제8
a = ['foo', 'bar', 'baz']
while True:   #break문이 없으면 영원히 실행됨
    if not a: #a가 False가 되면 not이 있어서 True가 되니까 빠져나온다.
        break
    print(a.pop())
    
baz
bar
foo

 

 

 

 

 

+ Recent posts