Skip to content

if-elif-else

조건식이 여러 개인 경우 중첩 if를 사용할 수 있지만 코드의 간결성이 떨어진다. 조건식이 여러 개일 경우 if-elif-else를 사용하는 것이 좋다.

python
if 조건식1:
    조건1이 참일 때 실행할 코드
elif 조건식2:
    조건2가 참일 때 실행할 코드
...
elif 조건식n:
    조건n이 참일 때 실행할 코드
else:
    조건이 거짓일 때 실행할 코드

elifelse if의 줄임말이다.

if-elif-else 문을 사용하여 예제 코드를 개선하면 다음과 같다.

python
score = int(input())
if score >= 90:
    print('A')
elif score >= 80:
    print('B')
elif score >= 70:
    print('C')
elif score >= 60:
    print('D')
else:
    print('F')

Powered by vitepress-logo-mini