Python은 "읽기 쉬운 코드"를 철학으로 가진 언어입니다. 같은 결과를 내더라도 "Pythonic"하게 작성하는 것이 Python 커뮤니티에서 권장됩니다.
Python is a language with a philosophy of "readable code." Even when achieving the same result, writing "Pythonically" is recommended in the Python community.
Simple is better than complex.
Readability counts."
— The Zen of Python
이 가이드에서는 Python의 핵심 문법과 실무에서 자주 사용하는 패턴을 설명합니다.
This guide explains Python's core syntax and patterns commonly used in practice.
리스트 컴프리헨션 (List Comprehension) List Comprehension
Python에서 가장 많이 사용되는 패턴 중 하나입니다. 반복문과 조건문을 한 줄로 표현하여 리스트를 생성합니다.
One of the most used patterns in Python. Creates lists by expressing loops and conditions in a single line.
❌ 일반적인 방법
❌ Traditional way
for x in range(10):
squares.append(x ** 2)
✅ Pythonic 방법
✅ Pythonic way
evens = [x for x in range(20) if x % 2 == 0]
# 딕셔너리 컴프리헨션
squares_dict = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# 집합 컴프리헨션
unique_lengths = {len(word) for word in ['hello', 'world', 'python']}
evens = [x for x in range(20) if x % 2 == 0]
# Dictionary comprehension
squares_dict = {x: x ** 2 for x in range(5)}
# {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Set comprehension
unique_lengths = {len(word) for word in ['hello', 'world', 'python']}
f-string (포맷 문자열) f-string (Formatted String Literals)
Python 3.6에서 도입된 f-string은 문자열 포맷팅의 가장 현대적이고 직관적인 방법입니다.
Introduced in Python 3.6, f-strings are the most modern and intuitive way of string formatting.
version = 3.12
# f-string 기본 사용
message = f"Hello, {name}!"
# 표현식 사용
result = f"2 + 3 = {2 + 3}"
# 포맷 지정자
price = 1234.5678
formatted = f"Price: {price:.2f}" # "Price: 1234.57"
# 정렬과 패딩
f"{name:>10}" # " Python" (오른쪽 정렬)
f"{name:^10}" # " Python " (중앙 정렬)
version = 3.12
# Basic f-string usage
message = f"Hello, {name}!"
# Using expressions
result = f"2 + 3 = {2 + 3}"
# Format specifiers
price = 1234.5678
formatted = f"Price: {price:.2f}" # "Price: 1234.57"
# Alignment and padding
f"{name:>10}" # " Python" (right align)
f"{name:^10}" # " Python " (center align)
with 문과 컨텍스트 매니저 with Statement and Context Managers
파일 처리, 데이터베이스 연결 등 리소스 관리에 필수적인 패턴입니다. 예외가 발생해도 리소스가 안전하게 정리됩니다.
An essential pattern for resource management like file handling and database connections. Resources are safely cleaned up even if exceptions occur.
with open('data.txt', 'r') as f:
content = f.read()
# 여러 파일 동시 처리
with open('input.txt') as src, open('output.txt', 'w') as dst:
dst.write(src.read())
# 데이터베이스 연결 예시
with db.connect() as conn:
result = conn.execute(query)
# 자동으로 commit/close
with open('data.txt', 'r') as f:
content = f.read()
# Multiple files at once
with open('input.txt') as src, open('output.txt', 'w') as dst:
dst.write(src.read())
# Database connection example
with db.connect() as conn:
result = conn.execute(query)
# Auto commit/close
언패킹과 다중 할당 Unpacking and Multiple Assignment
Python의 강력한 기능 중 하나로, 여러 값을 한 번에 할당하거나 분해할 수 있습니다.
One of Python's powerful features that allows assigning or decomposing multiple values at once.
a, b, c = 1, 2, 3
# 값 교환 (다른 언어에서는 임시 변수 필요)
a, b = b, a
# 나머지 수집 (*)
first, *rest = [1, 2, 3, 4, 5]
# first = 1, rest = [2, 3, 4, 5]
# 함수 반환값 언패킹
def get_user():
return 'Kim', 25, 'Seoul'
name, age, city = get_user()
a, b, c = 1, 2, 3
# Swap values (other languages need temp variable)
a, b = b, a
# Collect rest (*)
first, *rest = [1, 2, 3, 4, 5]
# first = 1, rest = [2, 3, 4, 5]
# Unpacking function return
def get_user():
return 'Kim', 25, 'Seoul'
name, age, city = get_user()
데코레이터 (Decorator) Decorators
함수나 클래스의 동작을 수정하거나 확장하는 강력한 도구입니다. 로깅, 인증, 캐싱 등에 널리 사용됩니다.
A powerful tool for modifying or extending the behavior of functions or classes. Widely used for logging, authentication, caching, etc.
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"실행 시간: {time.time() - start:.2f}초")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "완료"
import time
def timer(func):
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"Execution time: {time.time() - start:.2f}s")
return result
return wrapper
@timer
def slow_function():
time.sleep(1)
return "Done"
람다 함수와 내장 함수 Lambda Functions and Built-in Functions
square = lambda x: x ** 2
# map: 모든 요소에 함수 적용
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
# filter: 조건에 맞는 요소만
evens = list(filter(lambda x: x % 2 == 0, numbers))
# sorted: 정렬 (key 함수 활용)
users = [('Kim', 30), ('Lee', 25), ('Park', 35)]
by_age = sorted(users, key=lambda u: u[1])
# enumerate: 인덱스와 값 동시 순회
for idx, value in enumerate(numbers):
print(f"{idx}: {value}")
# zip: 여러 리스트 동시 순회
names = ['a', 'b', 'c']
scores = [90, 85, 88]
for name, score in zip(names, scores):
print(f"{name}: {score}")
square = lambda x: x ** 2
# map: Apply function to all elements
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x ** 2, numbers))
# filter: Keep only matching elements
evens = list(filter(lambda x: x % 2 == 0, numbers))
# sorted: Sort with key function
users = [('Kim', 30), ('Lee', 25), ('Park', 35)]
by_age = sorted(users, key=lambda u: u[1])
# enumerate: Iterate with index
for idx, value in enumerate(numbers):
print(f"{idx}: {value}")
# zip: Iterate multiple lists together
names = ['a', 'b', 'c']
scores = [90, 85, 88]
for name, score in zip(names, scores):
print(f"{name}: {score}")
타입 힌트 (Type Hints) Type Hints
Python 3.5부터 도입된 타입 힌트는 코드 가독성과 IDE 지원을 향상시킵니다.
Type hints, introduced in Python 3.5, improve code readability and IDE support.
def greet(name: str) -> str:
return f"Hello, {name}"
def sum_numbers(numbers: List[int]) -> int:
return sum(numbers)
def find_user(user_id: int) -> Optional[Dict]:
# None을 반환할 수도 있음
return users.get(user_id)
def greet(name: str) -> str:
return f"Hello, {name}"
def sum_numbers(numbers: List[int]) -> int:
return sum(numbers)
def find_user(user_id: int) -> Optional[Dict]:
# May return None
return users.get(user_id)
💡 왜 이 패턴들이 타자 연습에 포함되었는가? 💡 Why Are These Patterns Included in Typing Practice?
리스트 컴프리헨션, f-string, with 문은 Python 코드에서 매일 마주치는 패턴입니다. 이 패턴들을 손에 익히면 Python 코드를 더 빠르고 정확하게 작성할 수 있습니다.
List comprehensions, f-strings, and with statements are patterns you encounter daily in Python code. Internalizing these patterns helps you write Python code faster and more accurately.