python) 반복문

jun_legend·2021년 5월 23일
0

Python-Syntax

목록 보기
3/7
post-thumbnail

"반복문"

비슷한 형태의 작업을 반복할 수 있게 해주는 구문


[ for in 반복문 ]

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 반복문 ]

while 조건문:

  • 조건문이 True 면 계속 반복하고,
  • 조건문이 False 면 반복을 멈춘다.


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
  • break 키워드를 만나면 반복문을 빠져나간다.

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
  • continue 키워드를 만나면 처음 반복으로 돌아간다.


while 반복문은 조건문을 기반으로 작성하며
조건문이 True면 무한 반복을 구현할 수 있는 반면,

for in 반복문은 무한 반복을 구현할 수 없다.

0개의 댓글