Python 조건문 마스터하기: IF, ELSE, ELIF, 스위치류 로직
Python에서 조건문이란?
조건문은 불리언 표현식에 따라 다른 코드 블록 실행 가능하게 합니다. Python에서 if 문이 이 의사결정 과정을 이끄는 핵심 구조입니다.
이 가이드에서 if, else, elif, Python의 딕셔너리 기반 스위치-케이스 대안 사용법 탐구. 각 섹션에 개념 설명용 간결 예제 포함.
if 문 이해
if 조건 실패 시
else 절 사용
else 흔한 함정
elif로 다중 분기
- 삼항 표현식으로 로직 간소화
- 중첩
if 문
- 딕셔너리로 스위치-케이스 패턴 구현
Python if 문 기초
문법
if expression:
# 표현식이 True일 때 실행 블록
else:
# 표현식이 False일 때 실행 블록
예제:
def main():
x, y = 2, 8
if x < y:
st = "x is less than y"
else:
st = "x is not less than y"
print(st)
if __name__ == "__main__":
main()
if 조건이 거짓일 때
조건이 False로 평가되고 else 절 없으면 if 본문 건너뛰고 블록 뒤부터 계속 실행.
실패 조건 예제:
def main():
x, y = 8, 4
if x < y:
st = "x is less than y"
else:
st = "x is greater than or equal to y"
print(st)
if __name__ == "__main__":
main()
else 절 사용
else 블록은 앞선 if 조건이 False일 때 실행. 이진 결정 시 유용.
def main():
x, y = 8, 4
if x < y:
st = "x is less than y"
else:
st = "x is greater than y"
print(st)
if __name__ == "__main__":
main()
else 흔한 실수
두 값이 같을 때 else 블록이 비교를 '크다' 또는 '작다'로 잘못 보고할 수 있음.
def main():
x, y = 8, 8
if x < y:
st = "x is less than y"
else:
st = "x is greater than y" # x == y일 때 부정확
print(st)
if __name__ == "__main__":
main()
elif로 다중 분기 도입
elif 절은 초기 if 뒤 추가 조건 테스트 허용. 위 낙하 오류 방지.
def main():
x, y = 8, 8
if x < y:
st = "x is less than y"
elif x == y:
st = "x is the same as y"
else:
st = "x is greater than y"
print(st)
if __name__ == "__main__":
main()
삼항 표현식으로 로직 압축
Python 한 줄 문법으로 단순 비교 간결화:
def main():
x, y = 10, 8
st = "x is less than y" if x < y else "x is greater than or equal to y"
print(st)
if __name__ == "__main__":
main()
중첩 if 문
결정이 여러 변수에 의존할 때 중첩 조건 유용.
total = 100
country = "AU" # "US"로 변경해 다른 블록 테스트
if country == "US":
if total <= 50:
print("Shipping Cost is $50")
elif total <= 100:
print("Shipping Cost is $25")
elif total <= 150:
print("Shipping Costs $5")
else:
print("FREE")
elif country == "AU":
if total <= 50:
print("Shipping Cost is $100")
else:
print("FREE")
Python에서 스위치-케이스 대안
Python에 네이티브 switch 문 없지만 딕셔너리 조회로 같은 명확성과 효율성 제공.
def switch_example(argument):
switcher = {
0: "This is Case Zero",
1: "This is Case One",
2: "This is Case Two",
}
return switcher.get(argument, "nothing")
if __name__ == "__main__":
argument = 1
print(switch_example(argument))
요약
- if – 조건 참일 때 실행.
- else – 앞선
if 거짓일 때 실행.
- elif – 순차적 추가 불리언 체크.
- 한 줄(삼항) 표현식으로 단순 비교 간소화.
- 중첩
if 블록으로 다차원 결정 처리.
- 딕셔너리 조회로 깔끔한 스위치-케이스 대안 제공.