Python 의 분기는 다른 언어의 분기랑 비슷해 — if, elif, else. 근데 Pythonic 하게 만드는 두 가지가 있어. 첫째 — 조건이 boolean 일 필요가 없어. 어떤 객체든 truthiness 가 있고, 언어가 그걸 써. 둘째 — if x == True 같은 거 거의 안 써. if x 라고 쓰고 언어가 알아서 하게 해.
Truthiness — 모든 컨테이너가 따르는 규칙
빈 컨테이너는 falsy. None 도 falsy. 0 (어떤 숫자 타입이든) 도 falsy. 빈 문자열도 falsy. 나머지 (디폴트로) 다 truthy. 그래서 if my_list: 가 "my_list 가 비어있지 않으면" 으로 깨끗하게 읽혀. if user is not None: 은 None 과 빈 컨테이너를 *구분해야* 할 때 — "사용자 없음" 과 "친구 없는 사용자" 는 진짜 다르거든.
조건부 식 — Python 스타일 ternary
다른 언어들 — condition ? a : b. Python — a if condition else b. 영어 어순 그대로. 짧은 값 선택용으로 써. 한 번 이상 중첩하지 마. (a if c1 else b) if c2 else (c if c3 else d) 쓰고 있는 자신을 발견하면 가독성 한계 넘은 거 — 진짜 if 문 써.
원칙:== True 또는 == False 비교 X. if flag: 와 if not flag: 가 더 명확하고, 값이 엄격한 boolean 이 아닐 때 미묘한 버그도 안 만들어.
체인 비교 — 모를 수도 있는 문법
Python 은 1 < x < 10 을 한 식으로 허용해. (1 < x) and (x < 10) 처럼 평가하지만 x 는 한 번만 계산. 범위 체크, 나이 경계, 두 비교가 페어로 가는 곳 어디든 좋아. 다른 언어들엔 거의 없어서 C/Java 출신 엔지니어들이 놀라.
Pythonic Way:if/elif 체인이 4-5 분기 넘고 키 lookup 해서 분기하는 거면 dict 써. handlers = {"a": fn_a, "b": fn_b} + handlers[key](). Python 3.10 의 match 도 있어 — 구조 매칭이 필요하면. 다음 lesson 에서.
Code
Truthiness — 코드로 보는 규칙·python
# Falsy 값들
for x in [None, False, 0, 0.0, "", [], {}, set(), ()]:
if x:
print("truthy")
else:
print("falsy")
# 다 'falsy' 출력
# idiomatic 빈 체크
items = []
if items: # vs. if len(items) > 0:
print("have items")
else:
print("empty") # 이게 출력
# 근데 — None 과 empty 는 다른 거
user = None
if user is None:
print("사용자 자체가 없음")
elif not user:
print("사용자는 있는데 비어있음")
else:
print("내용 있는 사용자")
조건부 식 — Python ternary·python
n = 7
label = "odd" if n % 2 else "even"
print(label) # 'odd'
# 흔함: 디폴트 값 선택
user_input = ""
name = user_input or "anonymous"
print(name) # 'anonymous'
# `or` 는 첫 truthy 값을 반환 — 반드시 True 가 아님
print(0 or 5 or 99) # 5
print([] or [1]) # [1]
# `and` 는 첫 falsy 값 또는 마지막 값 반환
print(1 and 2 and 3) # 3
print(1 and 0 and 3) # 0 (short-circuit)
체인 비교 — Python 의 특별함·python
x = 5
# 체인 — Python 만
if 1 < x < 10:
print("in range")
# 같은 의미
if 1 < x and x < 10:
print("same idea")
# 근데 — x 는 한 번만 평가됨
def get_x():
print("computing x")
return 5
if 1 < get_x() < 10:
print("computed once")
# 'computing x' 한 번만 출력
== True / == False 비교 X·python
active = True
# 안 좋음
if active == True:
pass
# 좋음
if active:
pass
# 더 중요한 이유 — active 가 truthy 인데 진짜 True 가 아닐 때
active = 1 # int 1, bool True 가 아님
if active == True: # True (1 == True 가 True 라서)
print("compares")
active = "yes"
if active == True: # False
print("이건 안 출력")
if active: # truthy
print("이건 출력")
함수 classify(score) 작성 — 점수가 100 이면 "perfect", 70 <= score < 100 이면 "pass", 0 <= score < 70 이면 "retry", 그 외 (음수, 100 초과, None, 비숫자) 면 "invalid". 도움 되는 곳에 체인 비교 써, 어딘가에 조건부 식 써, None 처리는 if x is None 으로 명시적. 최소 6 입력으로 테스트.
Progress
Progress is local-only — sign in to sync across devices.