Python
인터프리터 언어. 간결한 문법으로 데이터 분석, 웹 백엔드, 자동화 등 폭넓게 사용.
기본 문법
# 변수 (타입 선언 불필요)
name = "김탄"
age = 30
is_active = True
# 타입 힌트 (선택, Python 3.5+)
name: str = "김탄"
age: int = 30자료형
# 리스트 (가변)
nums = [1, 2, 3]
nums.append(4)
nums[0] # 1
nums[-1] # 4 (뒤에서)
nums[1:3] # [2, 3] (슬라이싱)
# 튜플 (불변)
point = (10, 20)
# 딕셔너리
user = {"name": "김탄", "age": 30}
user["name"] # 김탄
user.get("email", "") # 없으면 기본값
# 셋
tags = {"python", "dev"}
tags.add("backend")제어문
# 조건문
if age >= 18:
print("성인")
elif age >= 13:
print("청소년")
else:
print("어린이")
# 반복문
for i in range(5): # 0~4
print(i)
for item in nums:
print(item)
while condition:
break / continue함수
def greet(name: str, greeting: str = "안녕") -> str:
return f"{greeting}, {name}!"
# 가변 인자
def sum_all(*args):
return sum(args)
# 키워드 인자
def create_user(**kwargs):
return kwargs # {"name": "김탄", "age": 30}
# 람다
double = lambda x: x * 2
# 리스트 컴프리헨션
squares = [x**2 for x in range(10)]
evens = [x for x in range(10) if x % 2 == 0]클래스
class Animal:
def __init__(self, name: str):
self.name = name
def speak(self) -> str:
return ""
class Dog(Animal):
def speak(self) -> str:
return f"{self.name}: 왈왈"
dog = Dog("멍멍이")
print(dog.speak())예외 처리
try:
result = 10 / 0
except ZeroDivisionError as e:
print(f"오류: {e}")
except (TypeError, ValueError):
print("타입 또는 값 오류")
else:
print("성공") # 예외 없을 때만 실행
finally:
print("항상 실행")파일 I/O
# 쓰기
with open("file.txt", "w", encoding="utf-8") as f:
f.write("내용")
# 읽기
with open("file.txt", "r", encoding="utf-8") as f:
content = f.read()
lines = f.readlines()유용한 내장 함수
len([1,2,3]) # 3
sorted([3,1,2]) # [1,2,3]
sorted(users, key=lambda u: u["age"], reverse=True)
enumerate(["a","b"]) # (0,"a"), (1,"b")
zip([1,2], ["a","b"]) # (1,"a"), (2,"b")
map(str, [1,2,3]) # ["1","2","3"]
filter(lambda x: x>1, [1,2,3]) # [2,3]
any([False, True]) # True
all([True, True]) # True자주 쓰는 라이브러리
| 라이브러리 | 용도 |
|---|---|
requests |
HTTP 요청 |
FastAPI / Flask |
웹 서버 |
pandas |
데이터 분석 |
numpy |
수치 연산 |
pytest |
테스트 |
pydantic |
데이터 검증 |
SQLAlchemy |
ORM |
python-dotenv |
환경 변수 |