'파이썬 프로그램 흐름 제어'에 해당되는 글 1건

  1. 2017.09.03 [Python] 파이썬 if, elif, else 분기문 (Python if, elif, else, nested if branch statement)

지난 포스팅에서는 파이썬 프로그래밍에 들어가기에 앞서 파이썬이 어떻게 참(True), 거짓(False)을 평가, 판단하는지에 대한 기본 문법을 알아보았습니다. 


이번 포스팅부터는 파이썬 프로그램의 흐름을 제어(Python progmram flow control)하는 방법에 대해서 몇 개 포스팅으로 나누어서 소개를 하겠습니다. 


파이썬 프로그램 흐름 제어에서 알아야 할 큰 2가지 뼈대가 있다면 


- (1) 조건이 참(True), 거짓(False)인지에 따라 프로그램 흐름을 나누어 주는 분기문(Branch statements)

       : if statements

       : if, else statements

       : if, elif, else statements

       : nested if statements


- (2) 조건이 참이거나 순서열의 끝까지 반복, 중단하게 해주는 반복문

       : while

       : for

       : continue, break


가 있습니다. 


이번 포스팅에서는 먼저 if, elif, else 분기문(Branch statement)에 대해서 알아보겠습니다. 



[ 파이썬 프로그램 흐름 제어 (Python program flow control) ]






먼저 if, else 분기문에서 사용하는 용어를 간단히 짚어보고 넘어가겠습니다. 


  • if 조건문에는 참(True), 거짓(False)을 평가할 수 있는 조건을 써주고, 마지막에는 콜론(:)을 붙여줍니다.
  • if 조건문이 거짓이면 'else:' 조건문으로 프로그램 흐름이 넘어가게 되며, 역시 마지막 부분에 콜론(:)을 붙여줍니다. 
  • if, else 조건문 아래의 컴퓨터에게 시킬 일을 적어놓은 부분은 'Code Block'라고 합니다. 
  • Code Block 은 '들여쓰기(indentation)'를 해서 구분을 해줍니다. 보통 space bar로 4칸 사용합니다. 
    (R, Java, C 등은 중괄호 { } 를 사용)


[ 파이썬 if, else 분기문 예시 (example of Python if, else branch statement) ]




이제 파이썬의 if, else 분기문을 가지고 간단한 프로그램을 하나 짜보도록 하겠습니다. 


 (1) 조건이 1개 일 때 if, else 분기문 (if, else branch statement with 1 condition)


파이썬이 해야 하는 일의 흐름은, 

  • (1-1) 파이썬 시험 점수를 입력받아서

  • (1-2) 만약 파이썬 시험 점수가 80점 이상이면 (if 조건문 True)
    "당신의 파이썬 점수는 xx점입니다. 축하합니다. 파이썬 시험을 통과하였습니다. :-)"
    를 출력하고, 종료. 

  • (1-3) 만약 파이썬 시험 점수가 80점 이상이 아니면 (if 조건문 False)
    "당신의 파이썬 점수는 xx점입니다. 파이썬 시험을 낙제했습니다. 공부 더 하세요. T_T"
    를 출력하고 종료. 

        [ Flow Diagram ]



위의 프로그램 흐름을 if, else 분기문을 사용해서 파이썬 프로그래밍을 해보면 아래와 같습니다. 



# (1) if, else statement


print('Put your Python test score : ')


py_score = int(input())


if py_score >= 80:

    

    print('Your Python score is {0}'.format(py_score))

    print('Congratulations! You passed Python test. :-)')

    

else:

    

    print('Your Python score is {0}'.format(py_score))

    print('You failed Python test. Study more! T_T')

 



아래에 파이썬 시험 점수가 90점일 때와 70점일 때 원하는 메시지대로 출력을 제대로 해주는지 시험해 보겠습니다. 



Put your Python test score :

90


Your Python score is 90

Congratulations! You passed Python test. :-)

 



Put your Python test score :

70


Your Python score is 70

You failed Python test. Study more! T_T

 



if 와 else 분기절의 마지막에 콜론(colon, :)을 실수로 빼먹으면 'SyntaxError: invalid syntax' 에러가 발생합니다. 



# If you miss colon(:) at the end, then 'SyntaxError: invalid syntax'

In [3]: print('Put your Python test score : ')

    ...:

    ...: py_score = int(input())

    ...:

    ...: if py_score >= 80 # Oops! Syntax Error due to no colon(:)

    ...:

    ...: print('Your Python score is {0}'.format(py_score))

    ...: print('Congratulations! You passed Python test. :-)')

    ...:

    ...:

    ...: else:

    ...:

    ...: print('Your Python score is {0}'.format(py_score))

    ...: print('You failed Python test. Study more! T_T')

    ...:

File "<ipython-input-18-b2c00ee4ee98>", line 5

if py_score >= 80 # Oops! Syntax Error due to no colon(:)

^

SyntaxError: invalid syntax

 




다음으로, 조건이 2개 이상일 때 if, elif, else 분기문 사용하는 법을 알아보겠습니다. elif 는 else if 의 줄임말로 보면 되겠습니다. 


 (2) 조건이 2개 일 때 if, elif, else 분기문 

      (if, elif, else branch statement with multiple condition expressions)


파이썬 시험 점수는 0점 ~ 100점 사이의 정수만 가능하고, 0점~100점 사이의 정수를 벗어나면 (예: -50점, 150점) '점수를 잘못입력했습니다'라는 안내 메시지를 출력하는 것으로 프로그램 코드를 좀더 똑똑하게 짜보겠습니다. 

  • (2-1) 파이썬 시험 점수를 입력받아서

  • (2-2) 만약 파이썬 시험 점수가 '80점 이상 ~ 100점 이하' 이면 
    "당신의 파이썬 점수는 xx점입니다. 축하합니다. 파이썬 시험을 통과하였습니다. :-)"를 출력하고, 종료. 

  • (2-3) 만약 파이썬 시험 점수가 '80점 이상 ~ 100점 이하'가 아니면서, '0점 이상 ~ 80점 미만'이면 
    "당신의 파이썬 점수는 xx점입니다. 파이썬 시험을 낙제했습니다. 공부 더 하세요. T_T"를 출력하고 종료. 

  • (2-4) 만약 파이썬 시험 점수가 '80점 이상 ~ 100점 이하'도 아니고, '0점 이상 ~ 80점 미만'도 아니면 
    "파이썬 시험 점수를 잘못 입력하였습니다" 를 출력하고 종료. 


       [ Flow Diagram ]




위의 (2-2) 프로그램 흐름을 파이썬 코드로 짜보면 아래와 같습니다.  if 조건문 안에 if 조건문을 중첩해서 쓸 수도 있구요, and, or 논리 연산자를 같이 쓸 수도 있습니다. 


# (2) if, elif, else statement


print('Put your Python test score : ')


py_score = int(input())


if py_score >= 80 and py_score <= 100:

    

    print('Your Python score is {0}'.format(py_score))

    print('Congratulations! You passed Python test')

    

elif py_score >= 0 and py_score < 80:

    

    print('Your Python score is {0}'.format(py_score))

    print('You failed Python test. Study more!')

    

else:

    

    print('You put the wrong score.')

 



파이썬 점수로 150점 (<- 잘못 입력), 90점(<- 시험 통과), 60점(<- 시험 낙제), -50점(<- 잘못 입력) 을 각 각 입력해보겠습니다. 



Put your Python test score : 

150


You put the wrong score.

 



Put your Python test score : 

90


Your Python score is 90

Congratulations! You passed Python test

 



Put your Python test score : 

60


Your Python score is 60

You failed Python test. Study more!

 



Put your Python test score : 

-50


You put the wrong score.

 




 (3) if 조건문 안에 if 조건문을 중첩해서 프로그래밍 하기 (nested if statements)


위의 (2)번 프로그램 흐름을 nested if statements를 사용해서 아래에 구현해 보았습니다. 위의 (2)번 if, elif, else 보다 더 복잡하고 코드도 길군요. 특히, nested if statements 를 사용할 때는 들여쓰기(indentation) 할 때 유의해야 합니다.  Spyder나 Pycharm 같은 IDE 의 Editor 창을 사용하면 자동으로 들여쓰기를 해줘서 실수를 방지하는데 도움이 됩니다. 



# (3) nested if statements

print('Put your Python test score : ')


py_score = int(input())


if py_score <= 100:

    if py_score >= 80:       

        print('Your Python score is {0}'.format(py_score))

        print('Congratulations! You passed Python test. :-)')

    

    else:       

        if py_score < 80:

            if py_score > 0:

                print('Your Python score is {0}'.format(py_score))

                print('You failed Python test. Study more! T_T')

                

            else:                

                print('You put the wrong score.')

        

else:    

    print('You put the wrong score.')

 



프로그램 흐름 제어 코드를 잘 짠건지 한번 시험을 해볼까요?  150점 (<- 잘못 입력), 90점 (<- 시험 통과), 60점 (<- 시험 낙제), -50점 (<- 잘못 입력)을 각 각 입력해보겠습니다.  아래 결과를 보니 파이썬 프로그램 코드를 제대로 짰네요. ^^



Put your Python test score : 

150


You put the wrong score.

 



Put your Python test score : 

90


Your Python score is 90

Congratulations! You passed Python test. :-)

 



Put your Python test score : 

60


Your Python score is 60

You failed Python test. Study more! T_T

 



Put your Python test score : 

-50


You put the wrong score.

 



많은 도움이 되었기를 바랍니다. 

이번 포스팅이 도움이 되었다면 아래의 '공감~'를 꾸욱 눌러주세요. 


다음 포스팅에서는 반복문(Loop statement)에 대해서 알아보겠습니다. 



728x90
반응형
Posted by Rfriend
,