Python 치트시트
데이터 타입, 함수, OOP, 파일 처리 등 Python 핵심 문법과 실전 패턴을 정리한 빠른 참조 가이드입니다.
데이터 타입 & 변수
6 itemsStrings
문자열 선언과 f-string 포매팅
name = "Vivory"
greeting = f"Hello, {name}!"
multiline = """First line
Second line"""
raw = r"C:\Users\path" # raw string (no escaping)Numbers
정수, 실수, 타입 변환
x = 42 # int
y = 3.14 # float
z = 1_000_000 # readable large number
int("42") # str -> int
float("3.14") # str -> float
round(3.14159, 2) # 3.14Lists
리스트 생성, 조작, 슬라이싱
nums = [1, 2, 3, 4, 5] nums.append(6) nums.extend([7, 8]) nums.insert(0, 0) first, *rest = nums # unpacking nums[-1] # last element nums[1:4] # slice [2, 3, 4] nums[::-1] # reverse
Dictionaries
딕셔너리 생성, 접근, 메서드
user = {"name": "Alice", "age": 30}
user["email"] = "alice@example.com"
user.get("phone", "N/A") # default if missing
user.keys() # dict_keys
user.values() # dict_values
user.items() # key-value pairs
{**user, "role": "admin"} # merge/spreadSets & Tuples
집합과 튜플
# Sets: unordered, unique elements
tags = {"python", "dev", "ai"}
tags.add("web")
tags & {"python", "web"} # intersection: {"python", "web"}
tags | {"rust"} # union
# Tuples: immutable sequences
point = (10, 20)
x, y = point # unpackingType Checking & Conversion
타입 확인 및 변환
type(42) # <class 'int'>
isinstance(42, int) # True
isinstance("hi", (str, int)) # True (any of)
list("hello") # ['h', 'e', 'l', 'l', 'o']
tuple([1, 2, 3]) # (1, 2, 3)
set([1, 1, 2]) # {1, 2}
bool(0) # False
bool("") # False제어 흐름
6 itemsif / elif / else
조건문
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
# Ternary
status = "pass" if score >= 60 else "fail"for loop
반복문 (시퀀스 순회)
for item in ["a", "b", "c"]:
print(item)
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)enumerate / zip
인덱스 포함 순회 및 병렬 순회
names = ["Alice", "Bob", "Charlie"]
for i, name in enumerate(names):
print(f"{i}: {name}")
scores = [90, 85, 78]
for name, score in zip(names, scores):
print(f"{name}: {score}")while / break / continue
while 반복문과 흐름 제어
count = 0
while count < 5:
if count == 3:
count += 1
continue # skip 3
print(count)
count += 1
while True:
data = input("Enter (q to quit): ")
if data == "q":
breakmatch / case (3.10+)
구조적 패턴 매칭
command = "start"
match command:
case "start":
print("Starting...")
case "stop" | "quit":
print("Stopping...")
case _:
print(f"Unknown: {command}")for / else
for-else 패턴 (break 없이 완료 시)
for n in range(2, 10):
for i in range(2, n):
if n % i == 0:
break
else:
# Only runs if inner loop had no break
print(f"{n} is prime")함수 & 람다
7 itemsdef / return
함수 정의와 반환
def greet(name: str, greeting: str = "Hello") -> str:
return f"{greeting}, {name}!"
result = greet("World")
result = greet("World", greeting="Hi")*args / **kwargs
가변 인자
def log(*args, **kwargs):
print("Args:", args)
print("Kwargs:", kwargs)
log(1, 2, 3, level="INFO", tag="app")
# Args: (1, 2, 3)
# Kwargs: {'level': 'INFO', 'tag': 'app'}lambda
익명 함수 (한 줄 함수)
square = lambda x: x ** 2
print(square(5)) # 25
# Commonly used with sorted/filter/map
users = [{"name": "Bob", "age": 25}, {"name": "Alice", "age": 30}]
sorted(users, key=lambda u: u["age"])Decorators
데코레이터 (함수 래핑)
import functools, time
def timer(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__}: {time.time() - start:.3f}s")
return result
return wrapper
@timer
def slow_func():
time.sleep(1)Generators (yield)
제너레이터 (지연 평가)
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fibonacci(10):
print(num)
# Generator expression
sum(x**2 for x in range(100))Type Hints
타입 힌트 (정적 타입 검사)
from typing import Optional, Union
def process(data: list[str], limit: int = 10) -> dict[str, int]:
return {item: len(item) for item in data[:limit]}
def find_user(user_id: int) -> Optional[dict]:
...
def parse(value: Union[str, int]) -> str:
return str(value)Multiple Return Values
여러 값 반환 (튜플 언패킹)
def min_max(nums: list[int]) -> tuple[int, int]:
return min(nums), max(nums)
lo, hi = min_max([3, 1, 4, 1, 5, 9])
print(f"min={lo}, max={hi}") # min=1, max=9컴프리헨션
6 itemsList Comprehension
리스트 컴프리헨션
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
# Equivalent to:
result = []
for x in range(10):
result.append(x**2)Dict Comprehension
딕셔너리 컴프리헨션
word_lengths = {w: len(w) for w in ["hello", "world", "python"]}
# {'hello': 5, 'world': 5, 'python': 6}
# Swap keys and values
original = {"a": 1, "b": 2}
swapped = {v: k for k, v in original.items()}Set Comprehension
집합 컴프리헨션 (중복 자동 제거)
unique_lengths = {len(w) for w in ["hi", "hello", "hey", "world"]}
# {2, 3, 5}Nested Comprehension
중첩 컴프리헨션
# Flatten a 2D list matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] flat = [x for row in matrix for x in row] # [1, 2, 3, 4, 5, 6, 7, 8, 9] # Create a 2D grid grid = [[0 for _ in range(3)] for _ in range(3)]
Conditional Comprehension
조건부 컴프리헨션
# Filter + transform valid_scores = [s * 10 for s in scores if s >= 60] # if-else (value expression, not filter) labels = ["even" if x % 2 == 0 else "odd" for x in range(5)] # ['even', 'odd', 'even', 'odd', 'even']
Walrus Operator (:=)
바다코끼리 연산자 (할당 표현식, 3.8+)
# Filter and use computed value
results = [y for x in data if (y := expensive_calc(x)) > threshold]
# Read lines until empty
while (line := input("Enter: ")) != "quit":
print(f"Got: {line}")문자열 연산
6 itemssplit / join
문자열 분할 및 결합
"hello world python".split() # ['hello', 'world', 'python']
"a,b,c".split(",") # ['a', 'b', 'c']
"one::two::three".split("::", 1) # ['one', 'two::three']
", ".join(["Alice", "Bob", "Charlie"])
# "Alice, Bob, Charlie"
"\n".join(lines)strip / replace
공백 제거, 문자열 치환
" hello ".strip() # "hello"
" hello ".lstrip() # "hello "
"hello world".replace("world", "Python")
"aabbaabb".replace("aa", "x", 1) # "xbbaabb" (max 1)startswith / endswith / in
문자열 시작/끝 확인, 포함 여부
filename = "report_2024.csv"
filename.startswith("report") # True
filename.endswith((".csv", ".tsv")) # True (tuple of suffixes)
"python" in "I love python" # Trueformat / f-string tricks
고급 문자열 포매팅
n = 42
f"{n:05d}" # "00042" (zero-pad)
f"{3.14159:.2f}" # "3.14" (2 decimals)
f"{1000000:,}" # "1,000,000" (comma sep)
f"{0.85:.1%}" # "85.0%" (percentage)
f"{'hello':>20}" # " hello" (right-align)Regex (re module)
정규 표현식
import re
re.search(r"\d+", "order-42-shipped") # <Match: '42'>
re.findall(r"[\w.]+@[\w.]+", text) # extract emails
re.sub(r"\s+", " ", messy_text) # normalize whitespace
pattern = re.compile(r"^\d{3}-\d{4}$")
pattern.match("123-4567") # matchesString Methods
유용한 문자열 메서드
"hello".upper() # "HELLO"
"HELLO".lower() # "hello"
"hello world".title() # "Hello World"
"Hello".isalpha() # True
"42".isdigit() # True
"hello world".count("l") # 3
"hello world".find("world") # 6 (-1 if not found)파일 입출력
5 itemsopen / read / write
파일 읽기와 쓰기 (with 문)
# Read entire file
with open("data.txt", "r", encoding="utf-8") as f:
content = f.read()
# Read lines
with open("data.txt") as f:
lines = f.readlines() # list of lines
# Write
with open("output.txt", "w") as f:
f.write("Hello\n")
# Append
with open("log.txt", "a") as f:
f.write("New entry\n")pathlib
경로 처리 (pathlib)
from pathlib import Path
p = Path("src/app/main.py")
p.name # "main.py"
p.stem # "main"
p.suffix # ".py"
p.parent # Path("src/app")
p.exists() # True/False
# Glob
for py in Path("src").rglob("*.py"):
print(py)JSON read / write
JSON 파일 읽기/쓰기
import json
# Read
with open("config.json") as f:
config = json.load(f)
# Write
with open("output.json", "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
# String conversion
json_str = json.dumps({"key": "value"})
obj = json.loads(json_str)CSV reader / writer
CSV 파일 처리
import csv
# Read
with open("data.csv") as f:
reader = csv.DictReader(f)
for row in reader:
print(row["name"], row["score"])
# Write
with open("output.csv", "w", newline="") as f:
writer = csv.DictWriter(f, fieldnames=["name", "score"])
writer.writeheader()
writer.writerow({"name": "Alice", "score": 95})Directory operations
디렉토리 생성, 삭제, 순회
import os, shutil
os.makedirs("output/reports", exist_ok=True)
os.listdir(".") # list directory
shutil.rmtree("build/") # remove directory tree
shutil.copytree("src/", "backup/src/")에러 처리
5 itemstry / except / finally
예외 처리 기본
try:
result = int(user_input)
data = 10 / result
except ValueError:
print("Not a valid number")
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
print("Cleanup here")raise
예외 발생시키기
def validate_age(age: int) -> None:
if age < 0:
raise ValueError(f"Age cannot be negative: {age}")
if age > 150:
raise ValueError(f"Age unrealistic: {age}")
# Re-raise current exception
try:
risky_operation()
except Exception:
logger.error("Operation failed")
raiseCustom Exceptions
사용자 정의 예외 클래스
class AppError(Exception):
"""Base exception for our app."""
class NotFoundError(AppError):
def __init__(self, resource: str, id: int):
self.resource = resource
self.id = id
super().__init__(f"{resource} #{id} not found")
try:
raise NotFoundError("User", 42)
except NotFoundError as e:
print(e) # "User #42 not found"assert
단언문 (디버깅/테스트용)
assert len(data) > 0, "Data cannot be empty"
assert isinstance(config, dict), f"Expected dict, got {type(config)}"
# Assertions are removed with python -O (optimized mode)
# Never use for input validation in productionLogging
로깅 (print 대신)
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s"
)
logger = logging.getLogger(__name__)
logger.info("Server started on port %d", 8000)
logger.warning("Disk usage at %d%%", 92)
logger.error("Connection failed", exc_info=True)객체 지향 프로그래밍
6 itemsclass / __init__
클래스 정의와 생성자
class User:
def __init__(self, name: str, email: str):
self.name = name
self.email = email
def greet(self) -> str:
return f"Hi, I'm {self.name}"
user = User("Alice", "alice@example.com")
print(user.greet())Inheritance
상속
class Animal:
def __init__(self, name: str):
self.name = name
def speak(self) -> str:
raise NotImplementedError
class Dog(Animal):
def speak(self) -> str:
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self) -> str:
return f"{self.name} says Meow!"
dog = Dog("Rex")
print(dog.speak()) # "Rex says Woof!"@property
프로퍼티 (getter/setter)
class Circle:
def __init__(self, radius: float):
self._radius = radius
@property
def radius(self) -> float:
return self._radius
@radius.setter
def radius(self, value: float):
if value < 0:
raise ValueError("Radius must be positive")
self._radius = value
@property
def area(self) -> float:
return 3.14159 * self._radius ** 2@staticmethod / @classmethod
정적 메서드와 클래스 메서드
class DateUtils:
@staticmethod
def is_leap_year(year: int) -> bool:
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
@classmethod
def from_string(cls, date_str: str) -> "DateUtils":
# Alternative constructor
return cls()
DateUtils.is_leap_year(2024) # True (no instance needed)dataclass
데이터 클래스 (보일러플레이트 감소)
from dataclasses import dataclass, field
@dataclass
class Product:
name: str
price: float
tags: list[str] = field(default_factory=list)
@property
def display_price(self) -> str:
return f"${self.price:.2f}"
p = Product("Widget", 9.99, ["sale"])
print(p) # Product(name='Widget', price=9.99, tags=['sale'])__repr__ / __str__
객체 문자열 표현
class Point:
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def __repr__(self) -> str:
return f"Point({self.x}, {self.y})"
def __str__(self) -> str:
return f"({self.x}, {self.y})"
def __eq__(self, other) -> bool:
return self.x == other.x and self.y == other.y
print(Point(1, 2)) # (1, 2) — uses __str__
print(repr(Point(1, 2))) # Point(1, 2) — uses __repr__Python 치트시트 사용 가이드
Python은 웹 개발, 데이터 과학, AI, 자동화 등 다양한 분야에서 가장 많이 사용되는 프로그래밍 언어입니다. 이 치트시트는 데이터 타입부터 OOP까지 Python 핵심 문법을 실전 예제와 함께 정리한 빠른 참조 가이드입니다.
Python 코딩 스타일
PEP 8 스타일 가이드를 따르세요. 들여쓰기는 스페이스 4칸, 변수/함수는 snake_case, 클래스는 PascalCase를 사용합니다. 한 줄은 79자(코드) 또는 72자(주석)를 넘기지 않는 것이 좋습니다.
Python 가상 환경
python -m venv .venv로 가상 환경을 만들고, source .venv/bin/activate로 활성화합니다. pip install -r requirements.txt로 의존성을 설치하고, pip freeze > requirements.txt로 현재 패키지 목록을 저장합니다.