비슷한 형태의 작업을 반복할 수 있게 해주는 구문
for 반복자 in 반복할 수 있는 것
1) for in 문자열
for character in "HELLO": print(character)
실행결과> H E L L O
2) for in 리스트
list_hello = ['H', 'E', 'L', 'L', 'O'] for element in list_hello: print(element)
실행결과> H E L L O
3) for in 딕셔너리
dict_hello = {'안':'H', '녕':'E', '하':'L', '세':'L', '요':'O'} for key in dict_hello: print(key, ':', dict_hello[key])
실행결과> 안 : H 녕 : E 하 : L 세 : L 요 : O
4) for in 반복문 응용
for i, element in enumerate():
list_hello = ['H', 'E', 'L', 'L', 'O'] for i, element in enumerate(list_hello): print("{}번쨰 요소는 {}입니다.".format(i, element))
실행결과> 0번쨰 요소는 H입니다. 1번쨰 요소는 E입니다. 2번쨰 요소는 L입니다. 3번쨰 요소는 L입니다. 4번쨰 요소는 O입니다.
for key, value in dictionary.items():
dict_hello = {'안':'H', '녕':'E', '하':'L', '세':'L', '요':'O'} for key, value in dict_hello.items(): print("dict_hello[{}] = {}".format(key, value))
실행결과> dict_hello[안] = H dict_hello[녕] = E dict_hello[하] = L dict_hello[세] = L dict_hello[요] = O
while 조건문:
1) 무한 반복
while True: print(".", end="")
실행결과> ................................................................................................................................................................................................
2) while 반복문 형태
data = "HELLO" i = 0 while i < 5: print(data[i]) i += 1
실행결과> H E L L O
3) while 반복문 강제로 빠져나가기 (break)
data = "HELLO_WORLD" i = 0 while True: print(data[i]) i += 1 if data[i] == "W": break
실행결과> H E L L O
4) while 반복문 맨처음으로 돌아가기 (continue)
data = "안녕하세요_HELLO" i = 0 while i < len(data)-1: i += 1 if i < 6: continue print(data[i])
실행결과> H E L L O
while 반복문은 조건문을 기반으로 작성하며
조건문이 True면 무한 반복을 구현할 수 있는 반면,
for in 반복문은 무한 반복을 구현할 수 없다.