본문 바로가기
Python

[Python] if, elif, else statements

by ds31x 2023. 7. 28.

if, elif, else statements (조건분기문)

프로그램의 flow control를 담당함. (loop문과 함께)

Flow control을 위한 Control Structures에 대한 내용은 다음 URL을 참고.

http://ds31x.blogspot.com/2023/07/basic-control-structures-and-control.html

 

C언어의 if, else if, else 와 매우 유사함.


설명

다음은 이들 사용을 위한 간략한 예이다.

if condition:   # if statement
  if_block      # if statement's code block
elif condition: # elif statement
  elif_block    # elif statement's code block
else:           # else statement
  else_block    # else statement's code block
  • if, elif, elsekeywords 임.
  • conditionboolean value로 reduction 되는 expression을 가리킴
    (and, or등으로 여러 condition이 묶이더라도 최종적으로는 하나의 boolean value로 reduction 됨.
  • if, elif, else statementscompound statements이며 첫 라인이 :으로 끝나야 한다.
  • 이후 해당 condition 등이 True일 경우 실행될 code block이 위치한다
    (else의 경우 condition이 없음을 주의).
  • if statement는 위의 예에서 첫 라인과 둘째 라인에 해당하며,
    첫 라인의 condition이 True인 경우 if_block의 statements들이 수행됨.
  • elif statement는 위의 예에서 셋째와 넷째 라인에 해당한다. ( elif = else + if )
    • 항상 이전에 if statement 1개와 0개 이상의 elif statements 선행되어야 하며,
    • 앞선 ifelif statement들의 condition이 False이고 자신의 condition이 True인 경우에 자신의 elif_block이 수행된다.
  • else statement는 위의 예에서 다섯째와 마지막 라인에 해당한다.
    • 항상 이전에 if statement 1개와 0개 이상의 elif statements 선행되어야 하며,
    • 앞선 ifelif statement들의 condition이 False인 경우에만 자신의 else_block이 수행된다.

if statement는 단독으로 사용가능하지만, elifelse statements는 단독으로 사용할 수 없다. ifelse statements 사이에 elif statement가 없을 수도 있음.

  • 같은 indent level의 ifelif, else statements들은 오직 하나의 condition에 대한 code block만이 수행되게 된다.
  • 선행된 condition에 우선권이 있음.
    • 각각에 해당하는 경우, 위에 위치한 것이 수행됨.

실제 code example

age = int(input ("당신의 나이는?"))
if age < 18 :
    print('당신은 미성년자입니다.')
elif age < 65 :
    print('당신은 성인입니다.')
else age >=65 and age <200 :
    print('당신은 노인입니다.')
else:
    print('당신은 ...')

위의 예제는 다음으로 나누어져 출력이 이루어짐.

  • 18 미만인 경우,
  • 18 이상 65 미만인 경우
  • 65 이상 200 미만인 경우
  • 200 이상인 경우

중첩

if,elif, else statements 에서 각 code block에는 어떤 python statements도 놓일 수 있음.
즉, if statement 안에 if statement가 중첩가능함.

age = int(input('How old are you'))

if age >= 200:
    print('당신은 ...')
else:
    if age <18:
        print('당신은 미성년자입니다.')
    elif age <65:
        print('당신은 성인입니다.')
    else:
        print('당신은 노인입니다.')

즉, 3중 if statement 이상도 가능하다 (가능하다고 권장되는 건 아니다.).

그리고, 가급적이면 많은 경우에 해당하는 조건을 앞에서 처리하도록 하는 게 좋다.


참고 : code block이란

Python code에서 여러 line을 하나의 block으로 묶을 수 있음.

  • code block은 indent (들여 쓰기) level이 증가할 때 시작됨.
  • code block은 다른 code block을 포함할 수 있음 : nested block이 가능.
  • code block은 indent가 없거나, 자신을 포함한 code block의 indent level로 감소할 때 끝남.

같이 보면 좋은 자료

2023.10.06 - [Pages] - [Python] Control Structure and Control Flow

 

[Python] Control Structure and Control Flow

Control structure와 Control Flow란 무엇인가? http://ds31x.blogspot.com/2023/07/basic-control-structures-and-control.html Basic : Control Structures and Control Flow Control Structure 프로그램을 구성하는 statement (=excutable code)들이 실

ds31x.tistory.com

 


 

728x90