Home Python - 제어문
Post
Cancel

Python - 제어문

조건문

if문

1
2
3
4
if condition :
    statement1
else :
    statement2
  • Python의 if문은 Tab이 중요하다.
  • if문의 실행문이 두 개 이상일 경우, 실행문의 들여쓰기는 같아야 한다.
  • 1
    2
    3
    4
    5
    6
    
    if condition :
          statement1
          statement2
    statement3 # error!
    else :
          statement4
    
  • 예시)
1
2
3
4
if 1 == 0:
    print('true')
else :
    print('false')
  • 결과: false

elif문

  • c, java의 else if문
1
2
3
4
5
6
if condition1 :
    statement1
elif condition2 :
    statement2
else :
    statement3
  • 예시)
1
2
3
4
5
6
7
8
age = 10

if age >= 20 :
    print('성인입니다')
elif age >= 10 :
    print('10대 입니다')
else :
    print('베이비입니다')
  • 결과: 10대 입니다

중첩 if문

1
2
3
4
5
6
7
8
9
10
if condition1:
    if condition2:
        statement1
    ''' (여러 줄 주석)
    else : 
        statement2
    '''
    statement2 # condition2가 아닐 경우 실행 (condition1 = True, condition2 = False)
else:
    statement3
  • 예시)
1
2
3
4
5
6
7
8
9
10
11
12
age = 24

if age >= 20 : # 20살 이상이면서
    if age >= 25 : #25살이 넘었습니다
        print('먹을만큼 먹었습니다')
    """
    else :
        print('성인입니다')
    """
    print('성인입니다') # 25살이 넘지 않았습니다
else :
    print('민증이 없습니다')
  • 결과: 성인입니다

반복문

while문

1
2
while condition:
    statement
  • 예시)
1
2
3
4
cnt = 0
while cnt < 5 :
    print(cnt)
    cnt += 1
  • 결과 :
    • 0
    • 1
    • 2
    • 3
    • 4

break

  • break를 만나면 while문 종료
  • 예시)
    1
    2
    3
    4
    5
    6
    
    while True: # 무한루프
      end = 0
      if end == 5 :
          break # end가 5라면 while문 빠져나가기
      print(end)
      end += 1
    
  • 결과:
    • 0
    • 1
    • 2
    • 3
    • 4

for문

1
2
3
4
5
6
7
''' C , Java
for ( int item = 0; item < items.length; item++ ) { 
        statement 
    }
'''
for item in items:
    statement
  • 예시)
1
2
3
4
l = [1, 2, 3, 4]

for i in l :
    print(i)
  • 결과:
    1
    2
    3
    4

★range() 함수

  • 연속되는 숫자를 만들어주는 함수
  • 형태 : range(start, stop, step)
  • stop : 마지막 숫자 + 1
    • range(5) : 0, 1, 2, 3, 4
  • start : 시작되는 숫자
    • range(1, 5) : 1, 2, 3, 4
    • range(3, 5) : 3, 4
  • step : 숫자간 간격
    • range(2, 10, 2) : 2, 4, 8
  • for문에서 많이 사용됨
  • 예시)
1
2
for i in range(5):
    print(i)
  • 결과:
    0
    1
    2
    3
    4

중첩 for문

1
2
3
for item in items:
    for i in item:
        statement
  • 예시) 구구단 출력하기
1
2
3
for i in range(2, 10) :
    for j in  range(2, 10) :
        print("%d x %d = %d" %(i, j, i * j))
  • 결과:
    • 2 x 2 = 4
    • 2 x 3 = 6
    • 2 x 4 = 8
    • 9 x 7 = 63
    • 9 x 8 = 72
    • 9 x 9 = 81
This post is licensed under CC BY 4.0 by the author.

Python - 기본 문법

Python - 가상환경 만들기

Comments powered by Disqus.