📌 기본 문법
- 출력: print("Hello, world!")
- 주석: # 한 줄 주석, """여러 줄 주석"""
- 변수 선언: 타입 없이 바로 사용
x = 10 name = "Alice"
🔢 기본 자료형
- int, float, str, bool, None
- 형 변환: int("10"), str(3.14), bool(0)
📚 자료구조
# 리스트 arr = [1, 2, 3] # 튜플 tup = (1, 2) # 집합 s = {1, 2, 3} # 딕셔너리 d = {"a": 1, "b": 2}
🔁 조건문 & 반복문
# 조건문 if x > 0: ... elif x == 0: ... else: ... # 반복문 for i in range(5): print(i) while x > 0: x -= 1
🧩 함수
def add(a, b): return a + b # 기본값, 키워드 인자 def greet(name="Guest"): print("Hello", name) greet(name="Tom")
📦 클래스
class Person: def __init__(self, name): self.name = name def say_hi(self): print(f"Hi, I'm {self.name}")
⚙️ 기타 문법
- 리스트 컴프리헨션
squares = [x**2 for x in range(5)] - 람다 함수
f = lambda x: x + 1 - 예외 처리
try: 1 / 0 except ZeroDivisionError: print("Cannot divide by zero") finally: print("Done")
- with 문 (컨텍스트 매니저)
with open("file.txt") as f: data = f.read()
🧪 타입 힌트 (Python 3.5+)
def add(a: int, b: int) -> int: return a + b
🧰 이터레이터 & 제너레이터
# 제너레이터 함수 def count_up(): yield 1 yield 2 for i in count_up(): print(i) # 이터레이터 it = iter([1, 2, 3]) next(it) # 1
🏷 데코레이터
def decorator(func): def wrapper(): print("Before") func() print("After") return wrapper @decorator def hello(): print("Hello")
🧵 비동기 프로그래밍 (async/await)
import asyncio async def say_hello(): print("Hello") await asyncio.sleep(1) print("World") # asyncio.run(say_hello())
🔍 패턴 매칭 (Python 3.10+)
match command: case "start": print("Starting") case "stop": print("Stopping") case _: print("Unknown")
🪄 그 외 문법들(3.6~3.11에서 새로 추가된 것들)
📌 f-string (Python 3.6+)
name = "Alice" print(f"Hello, {name}")
📌 변수 주석 (Python 3.6+)
age: int = 30
📌 := (해치 연산자, walrus operator / Python 3.8+)
if (n := len(data)) > 10: print(f"Too long: {n}")
📌 exception group, except* (Python 3.11+)
try: ... except* ValueError as e: # 여러 예외 동시 처리 ...
⚙️ 모듈 & 패키지
# import 방식 import math from math import pi, sqrt
📐 형 검사용 유틸 (typing 모듈)
from typing import List, Dict, Tuple def process(data: List[int]) -> Dict[str, int]: ...
🧱 데이터 클래스 (Python 3.7+)
from dataclasses import dataclass @dataclass class Point: x: int y: int
'PYTHON' 카테고리의 다른 글
Python 기초를 배우며 (0) | 2025.04.12 |
---|