Post

Python 반복문 - while, for, break, continue, else

Python 반복문 - while, for, break, continue, else

Python 반복문 - while, for, break, continue, else

반복문

While문

1
2
while <조건식>:
    실행할 코드
  • if문과 다른점은 while문은 조건식이 True인 경우만 진행

ex. 사용자가 ‘안녕’ 이라고 할때까지 계속 입력을 요청받는 코드

1
2
3
4
5
greeting = ''

while greeting != "안녕":  
    greeting = input('안녕이라고 해줘:')
    
  • 위 코드 해설
    while greering == ‘안녕’이 아닌이유
    while문은 조건식이 true인 경우에 반복하기 때문에 입력받는 것이 안녕일 경우에는 반복문이 끝남.
    그렇게 때문에 안녕이 아닐 경우를 반복해야하기 때문임

for문

1
2
for variable in sequence:
    code
  • 정해진 범위 내의 반복
  • sequence: list, tuple, range, string

enumerate 예시

1
2
3
4
menus = ['엽떡', '청다', '신전']
for menu in enumerate(menus) :  
    print(menu[0])
    print(menu[1])
1
2
3
for idx, menu in enumerate(menus) :
    print(idx)
    print(menu)

둘 다 결과값 동일

1
2
3
4
5
엽떡
1
청다
2
신전
  • enumerate() : tuple 형태로 데이터가 출력되며 리스트의 인덱스를 출력해줌.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
blood_type ={
    'A' : 5,
    'B' : 4,
    'O' : 2,
    'AB' : 3
}

#### dictionary 반복
1. for key in dict:
2. for key in dict.keys():
3. for value in dict.values():
4. for key, value in dict.items():

#### 혈액형 list
for key in dict.keys():
    print(key)
    
#### 전체 data의 총합
result = 0
for value in blood_type.values():
    result = result + value

print(f'총인원은 {result}명입니다')

#### A형은 몇명, B형은 몇명
for key, value in blood_type.items():
    print(f'{key}형은 {value}명입니다')
    

Break

  • 반복문을 종료시키는 키워드 (그냥종료)
1
2
3
4
5
6
rice = ['보리','보리','보리','','보리','보리']
for i in rice:
    print(i)
    if i != "보리":
        print( "잡았다!")
        break

Continue

  • continue 이후의 코드를 실행하지 않고 다음 반복을 진행 (다음 순번으로 넘어감)
1
2
3
4
5
6
age = [10, 35, 20, 18, 9, 40]

for i in age:
    if i < 20:  #continue할(넘길) 조건식
        continue
    print(f'{i} 성인입니다.')

Else

  • else 문은 끝까지 반복이 진행된 후 실행
1
2
3
4
5
6
for i in range(10):
    if i > 100:
        break
    print(i)
else:  # break까지 해당하지 않았기 때문에 else문 실행
    print('break 못만남')
  • 결과값
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    break 못만남
    
1
2
3
4
5
6
for i in range(10):
    if i > 5:
        break
    print(i)
else:      # 끝까지 갔기 때문에 else문 실행안함
    print('break 못만남')
  • 결과값
    1
    2
    3
    4
    5
    6
    
    0
    1
    2
    3
    4
    5
    

    Pass

  • 아직 무언가를 쓸지 모르겠을 때 사용
1
2
if True:
    pass

Match

  • 최근에 들어온 문법
    1
    2
    3
    4
    5
    6
    7
    
    match value:
      case 조건:
          code
      case 조건:
          code
      case _:
          code
    
1
2
3
4
5
6
7
8
9
10
#status = 100
status = 404

match status:
    case 400:
        print('bad')
    case 404:
        print('not found')
    case _:
        print('something is wrong')
This post is licensed under CC BY 4.0 by the author.