# ❌ Unpythonic
animals = ['cat', 'dog', 'moose']
for i in range(len(animals)):
print(i, animals[i])
# ✅ Pythonic
for i, animal in enumerate(animals):
print(i, animal)
# 인덱스 필요 없으면 직접 순회
for animal in animals:
print(animal)
# ❌ Unpythonic
fileObj = open('spam.txt', 'w')
fileObj.write('Hello')
fileObj.close()
# ✅ Pythonic
with open('spam.txt', 'w') as fileObj:
fileObj.write('Hello')
# ❌ Unpythonic
if spam == None:
pass
# ✅ Pythonic
if spam is None:
pass
# ❌ Unpythonic
if is_valid == True:
pass
# ✅ Pythonic
if is_valid:
pass
if not is_valid:
pass
# ❌ Unpythonic - 백슬래시 이스케이프
path = 'C:\\Users\\Al\\Desktop'
# ✅ Pythonic - r 접두사
path = r'C:\Users\Al\Desktop'
name, age = 'Alice', 25
# ❌ Unpythonic
msg = "Hello, " + name + ". Age: " + str(age)
# ✅ Pythonic
msg = f"Hello, {name}. Age: {age}"
# 표현식도 가능
width, length = 10, 12
f"Area: {width * length}" # "Area: 120"
# ❌ Unpythonic
if 'key' in d:
value = d['key']
else:
value = 'default'
# ✅ Pythonic
value = d.get('key', 'default')
# 기본값 설정하면서 가져오기
value = d.setdefault('key', 'default')
# ❌ Unpythonic
if season == 'Winter':
holiday = "New Year's Day"
elif season == 'Spring':
holiday = 'May Day'
elif season == 'Summer':
holiday = 'Juneteenth'
else:
holiday = 'Personal day off'
# ✅ Pythonic
holiday = {
'Winter': "New Year's Day",
'Spring': 'May Day',
'Summer': 'Juneteenth',
'Fall': 'Halloween'
}.get(season, 'Personal day off')
# ❌ Unpythonic
if 42 < spam and spam < 99:
pass
# ✅ Pythonic
if 42 < spam < 99:
pass
# 할당 체이닝
spam = eggs = bacon = 'value'
# 비교 체이닝
spam == eggs == bacon == 'value' # True
# ❌ Unpythonic
if spam == 'cat' or spam == 'dog' or spam == 'moose':
pass
# ✅ Pythonic
if spam in ('cat', 'dog', 'moose'):
pass
numbers = [8, 16, 18, 19, 12, 1, 6, 7]
# ❌ Unpythonic - map
list(map(lambda n: str(n), numbers))
# ✅ Pythonic
[str(n) for n in numbers]
# ❌ Unpythonic - filter
list(filter(lambda n: n % 2 == 0, numbers))
# ✅ Pythonic
[n for n in numbers if n % 2 == 0]
# ✅ Pythonic - 간단한 경우만
message = 'Access granted' if condition else 'Access denied'
# ❌ Unpythonic - 중첩 금지
age_range = 'child' if age < 13 else 'teen' if age < 18 else 'adult'
# ✅ 복잡하면 if-elif-else 사용
if age < 13:
age_range = 'child'
elif age < 18:
age_range = 'teen'
else:
age_range = 'adult'