← 목록으로
단계 01

Python 기초 튜토리얼

변수·자료구조·제어문·함수·파일 입출력 등 데이터 처리에 필요한 Python 핵심 문법.

학습 순서

순서주제핵심
1변수와 자료형int, float, str, bool, 형변환
2자료구조list, tuple, dict, set — 언제 무엇을 쓰는지
3제어문if, for, while, 컴프리헨션
4함수매개변수, 반환값, lambda, 기본값 인자
5파일 입출력open, with, CSV/JSON 읽고 쓰기
6모듈과 패키지import, pip, 가상환경
7예외 처리try / except / finally

꼭 익혀야 할 패턴

딕셔너리와 리스트 컴프리헨션

sales = [
    {"region": "Seoul", "amount": 120},
    {"region": "Busan", "amount": 80},
    {"region": "Seoul", "amount": 50},
]

# 지역별 합계 — 나중에 Pandas의 groupby, Spark의 reduceByKey와 같은 개념
totals = {}
for row in sales:
    totals[row["region"]] = totals.get(row["region"], 0) + row["amount"]
print(totals)   # {'Seoul': 170, 'Busan': 80}

# 컴프리헨션
big = [r for r in sales if r["amount"] >= 100]

파일 읽기 (CSV / JSON)

import csv, json

with open("data.csv", newline="", encoding="utf-8") as f:
    for row in csv.DictReader(f):
        print(row["name"], row["score"])

with open("data.json", encoding="utf-8") as f:
    data = json.load(f)

함수와 map / filter

MapReduce, Spark의 map/filter/reduce가 바로 이 개념입니다.

nums = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x * x, nums))          # [1, 4, 9, 16, 25]
evens = list(filter(lambda x: x % 2 == 0, nums))    # [2, 4]

from functools import reduce
total = reduce(lambda a, b: a + b, nums)            # 15

연습 과제

  1. 학번·이름·점수가 든 CSV를 읽어서 평균 점수를 출력
  2. 점수가 80 이상인 학생만 새 CSV로 저장
  3. 위 작업을 함수로 분리하고 다른 파일에도 재사용

다음 단계(Pandas)에서는 위 작업을 코드 3줄로 줄이는 방법을 배웁니다.