for과 동일한 기능
but, for문은 이터레이터(for문은 list, set, dict등의 data structure 기반)를 이용하여 반복문 기능을 수행
while문은 조건이 "참"인 동안 내부의 실행문들을 반복 실행
while문은 특정 조건문이True일 동안 코드블록을 반복 실행특정 조건을 만족하는 동안 해당 코드들을 반복
num = 0 # num이 0부터 시작
while num <= 5: # num이 5보다 작거나 같을때 까지
print(num) # num을 출력해라
num += 1 # 그 후 num에 1을 더해라
#0
#1
#2
#3
#4
#5
ex1) 까페에서 손님을 다섯번 부르고, 찾으러오지 않으면 커피 폐기처분
customer = "Thor"
index = 5
while index >= 1:
print("{0}, your coffee is here. {1} left.".format(customer, index))
index -= 1
if index == 0:
print("your coffee is discarded.")
# Thor, your coffee is here. 5 left.
# Thor, your coffee is here. 4 left.
# Thor, your coffee is here. 3 left.
# Thor, your coffee is here. 2 left.
# Thor, your coffee is here. 1 left.
# your coffee is discarded.
ex2) 무한 루프
customer = "Thor"
index = 1
while True:
print("{0}, your coffee is here. {1}times called.".format(customer, index))
index += 1
# 무한정으로 호출을 계속함
# **CTRL + C 누르면 강제 종료**
ex3) 원하는 값이 input될 때까지 계속 진행, 원하는 input값이 입력되면 종료
customer = "Thor"
person = "Unknown"
while person != customer:
print("{0}, your coffee is here.".format(customer))
person = input("What is your name? ")
# Thor, your coffee is here.
# What is your name? iron
# Thor, your coffee is here.
# What is your name? thor
# Thor, your coffee is here.
# What is your name? Thor
# 종료(반복문 탈출)
break:: while문을 강제 종료
continue:: 다음 iteration으로 넘어감.
number = 0
while number <= 10:
if number == 9:
break
elif number <= 5:
number += 1
continue
else:
print(number)
number += 1
# 6
# 7
# 8
while 조건문이 False일 때 실행while 조건문이 종료되면 else 문이 실행while <조건문>:
<수행할 문장1>
<수행할 문장2>
<수행할 문장3>
...
<수행할 문장N>
else:
<while문이 종료된 후 수행할 문장1>
<while문이 종료된 후 수행할 문장2>
<while문이 종료된 후 수행할 문장3>
...
<while문이 종료된 후 수행할 문장N>