hobokai 님의 블로그

Python 완전 정복 가이드 - 1편: 기초편 본문

Language

Python 완전 정복 가이드 - 1편: 기초편

hobokai 2025. 8. 4. 10:29

Python 완전 정복 가이드 - 1편: 기초편

목차

  1. Python 소개
  2. 개발 환경 설정
  3. 기본 문법
  4. 데이터 타입
  5. 제어구조
  6. 함수
  7. 모듈과 패키지

Python 소개

Python이란?

Python은 1991년 귀도 반 로섬(Guido van Rossum)이 개발한 고급 프로그래밍 언어입니다. 간결하고 읽기 쉬운 문법으로 유명하며, "삶이 짧으니 Python을 쓰자(Life is short, use Python)"라는 철학을 가지고 있습니다.

Python의 특징

  • 간결한 문법: 들여쓰기로 코드 블록을 구분
  • 인터프리터 언어: 컴파일 없이 바로 실행
  • 크로스 플랫폼: Windows, macOS, Linux에서 동작
  • 풍부한 라이브러리: 방대한 표준 라이브러리와 서드파티 패키지
  • 객체지향: 모든 것이 객체

Python 활용 분야

  • 웹 개발 (Django, Flask)
  • 데이터 분석 (Pandas, NumPy)
  • 머신러닝/AI (TensorFlow, PyTorch)
  • 자동화/스크립팅
  • 게임 개발 (Pygame)

개발 환경 설정

Python 설치

# Windows
# python.org에서 공식 설치 프로그램 다운로드

# macOS (Homebrew 사용)
brew install python

# Ubuntu/Debian
sudo apt update
sudo apt install python3 python3-pip

# Python 버전 확인
python --version
python3 --version

가상환경 설정

# venv를 사용한 가상환경 생성
python -m venv myproject
cd myproject

# 가상환경 활성화
# Windows
Scripts\activate
# macOS/Linux
source bin/activate

# 패키지 설치
pip install requests pandas numpy

IDE 및 에디터 추천

  • PyCharm: 전문적인 Python IDE
  • VS Code: 가벼운 에디터 + Python 확장
  • Jupyter Notebook: 데이터 분석용
  • Sublime Text: 빠른 텍스트 에디터

기본 문법

Hello World

# 주석은 #으로 시작
print("Hello, World!")

# 여러 줄 주석
"""
이것은 여러 줄 주석입니다.
docstring으로도 사용됩니다.
"""

변수와 할당

# 동적 타이핑 - 타입을 명시하지 않음
name = "Python"
age = 30
height = 175.5
is_student = True

# 여러 변수 동시 할당
x, y, z = 1, 2, 3
a = b = c = 0

# 변수명 규칙
# - 문자, 숫자, 밑줄(_) 사용 가능
# - 숫자로 시작 불가
# - 예약어 사용 불가

들여쓰기 (Indentation)

# Python은 들여쓰기로 코드 블록을 구분
if True:
    print("들여쓰기 4칸")
    if True:
        print("중첩된 들여쓰기")

데이터 타입

숫자형 (Numbers)

# 정수 (int)
age = 25
negative = -10
binary = 0b1010  # 2진수
octal = 0o12     # 8진수
hex_num = 0xFF   # 16진수

# 실수 (float)
height = 175.5
scientific = 1.2e-4  # 과학적 표기법

# 복소수 (complex)
complex_num = 3 + 4j

# 연산자
print(10 + 3)   # 13 (덧셈)
print(10 - 3)   # 7 (뺄셈)
print(10 * 3)   # 30 (곱셈)
print(10 / 3)   # 3.333... (나눗셈)
print(10 // 3)  # 3 (몫)
print(10 % 3)   # 1 (나머지)
print(10 ** 3)  # 1000 (거듭제곱)

문자열 (String)

# 문자열 생성
single_quote = 'Hello'
double_quote = "World"
triple_quote = """여러 줄
문자열"""

# 문자열 연산
greeting = "Hello" + " " + "World"
repeat = "Python" * 3  # PythonPythonPython

# 문자열 인덱싱과 슬라이싱
text = "Python"
print(text[0])     # P (첫 번째 문자)
print(text[-1])    # n (마지막 문자)
print(text[2:5])   # tho (2~4번째 문자)
print(text[:3])    # Pyt (처음부터 2번째까지)
print(text[3:])    # hon (3번째부터 끝까지)

# 문자열 메서드
name = "python programming"
print(name.upper())        # PYTHON PROGRAMMING
print(name.lower())        # python programming
print(name.capitalize())   # Python programming
print(name.title())        # Python Programming
print(name.split())        # ['python', 'programming']
print("-".join(['a', 'b', 'c']))  # a-b-c

# 문자열 포매팅
name = "Alice"
age = 30

# f-string (Python 3.6+)
message = f"이름: {name}, 나이: {age}"

# format() 메서드
message = "이름: {}, 나이: {}".format(name, age)
message = "이름: {name}, 나이: {age}".format(name=name, age=age)

# % 포매팅 (구식)
message = "이름: %s, 나이: %d" % (name, age)

불린 (Boolean)

# 불린 값
is_true = True
is_false = False

# 비교 연산자
print(5 > 3)    # True
print(5 < 3)    # False
print(5 == 5)   # True
print(5 != 3)   # True
print(5 >= 5)   # True

# 논리 연산자
print(True and False)  # False
print(True or False)   # True
print(not True)        # False

# Truthy/Falsy 값
# Falsy: False, 0, "", [], {}, None
# Truthy: 나머지 모든 값
print(bool(0))      # False
print(bool(""))     # False
print(bool([]))     # False
print(bool({}))     # False
print(bool(None))   # False
print(bool("Hi"))   # True
print(bool([1]))    # True

리스트 (List)

# 리스트 생성
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]

# 리스트 접근
print(fruits[0])    # apple
print(fruits[-1])   # cherry (마지막 요소)
print(numbers[1:4]) # [2, 3, 4]

# 리스트 수정
fruits[0] = "orange"
fruits.append("grape")      # 끝에 추가
fruits.insert(1, "kiwi")    # 특정 위치에 삽입
fruits.remove("banana")     # 값으로 제거
popped = fruits.pop()       # 마지막 요소 제거 후 반환
fruits.extend(["mango", "peach"])  # 여러 요소 추가

# 리스트 메서드
numbers = [3, 1, 4, 1, 5]
print(len(numbers))        # 5 (길이)
print(numbers.count(1))    # 2 (1의 개수)
print(numbers.index(4))    # 2 (4의 인덱스)
numbers.sort()             # 정렬
numbers.reverse()          # 역순

튜플 (Tuple)

# 튜플 생성 (변경 불가능)
coordinates = (3, 5)
colors = ("red", "green", "blue")
single_tuple = (42,)  # 단일 요소 튜플

# 튜플 접근 (리스트와 동일)
print(coordinates[0])  # 3
print(colors[1:])      # ('green', 'blue')

# 튜플 언패킹
x, y = coordinates
print(f"x: {x}, y: {y}")  # x: 3, y: 5

# 튜플은 불변이므로 수정 불가
# coordinates[0] = 10  # TypeError 발생

딕셔너리 (Dictionary)

# 딕셔너리 생성
person = {
    "name": "Alice",
    "age": 30,
    "city": "Seoul"
}

# 딕셔너리 접근
print(person["name"])           # Alice
print(person.get("age"))        # 30
print(person.get("job", "N/A")) # N/A (기본값)

# 딕셔너리 수정
person["age"] = 31
person["job"] = "Engineer"
del person["city"]

# 딕셔너리 메서드
print(person.keys())    # dict_keys(['name', 'age', 'job'])
print(person.values())  # dict_values(['Alice', 31, 'Engineer'])
print(person.items())   # dict_items([('name', 'Alice'), ...])

# 딕셔너리 순회
for key in person:
    print(f"{key}: {person[key]}")

for key, value in person.items():
    print(f"{key}: {value}")

집합 (Set)

# 집합 생성 (중복 없음, 순서 없음)
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 3, 2, 1])  # {1, 2, 3}

# 집합 연산
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}

print(set1 | set2)  # {1, 2, 3, 4, 5, 6} (합집합)
print(set1 & set2)  # {3, 4} (교집합)
print(set1 - set2)  # {1, 2} (차집합)
print(set1 ^ set2)  # {1, 2, 5, 6} (대칭차집합)

# 집합 메서드
fruits.add("orange")
fruits.remove("banana")  # 없으면 KeyError
fruits.discard("grape")  # 없어도 에러 없음

제어구조

조건문 (if문)

# 기본 if문
age = 18

if age >= 18:
    print("성인입니다")
elif age >= 13:
    print("청소년입니다")
else:
    print("어린이입니다")

# 삼항 연산자
status = "성인" if age >= 18 else "미성년자"

# 여러 조건
score = 85
if 90 <= score <= 100:
    grade = "A"
elif 80 <= score < 90:
    grade = "B"
elif 70 <= score < 80:
    grade = "C"
else:
    grade = "F"

# in 연산자
fruits = ["apple", "banana", "cherry"]
if "apple" in fruits:
    print("사과가 있습니다")

반복문 (for문)

# 리스트 순회
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# 문자열 순회
for char in "Python":
    print(char)

# range() 사용
for i in range(5):          # 0, 1, 2, 3, 4
    print(i)

for i in range(1, 6):       # 1, 2, 3, 4, 5
    print(i)

for i in range(0, 10, 2):   # 0, 2, 4, 6, 8
    print(i)

# enumerate() - 인덱스와 값 함께
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")

# zip() - 여러 시퀀스 동시 순회
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(f"{name}: {age}세")

# 딕셔너리 순회
person = {"name": "Alice", "age": 30, "city": "Seoul"}
for key, value in person.items():
    print(f"{key}: {value}")

반복문 (while문)

# 기본 while문
count = 0
while count < 5:
    print(count)
    count += 1

# 무한 루프 (주의!)
# while True:
#     print("무한 반복")

# break와 continue
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
    if num == 5:
        continue  # 5는 건너뛰기
    if num == 8:
        break     # 8에서 루프 종료
    print(num)    # 1, 2, 3, 4, 6, 7

# else절 (break로 종료되지 않을 때만 실행)
for i in range(3):
    print(i)
else:
    print("정상 종료")  # 실행됨

for i in range(3):
    if i == 1:
        break
    print(i)
else:
    print("정상 종료")  # 실행되지 않음

함수

함수 정의와 호출

# 기본 함수
def greet():
    print("안녕하세요!")

greet()  # 함수 호출

# 매개변수가 있는 함수
def greet_person(name):
    print(f"안녕하세요, {name}님!")

greet_person("Alice")

# 반환값이 있는 함수
def add(a, b):
    return a + b

result = add(3, 5)
print(result)  # 8

# 여러 값 반환
def calculate(a, b):
    return a + b, a - b, a * b, a / b

sum_val, diff, product, quotient = calculate(10, 3)

매개변수와 인수

# 기본값 매개변수
def greet(name, greeting="안녕하세요"):
    print(f"{greeting}, {name}님!")

greet("Alice")              # 안녕하세요, Alice님!
greet("Bob", "Hi")          # Hi, Bob님!

# 키워드 인수
def introduce(name, age, city):
    print(f"이름: {name}, 나이: {age}, 도시: {city}")

introduce(age=30, name="Alice", city="Seoul")

# 가변 인수 (*args)
def sum_all(*numbers):
    return sum(numbers)

print(sum_all(1, 2, 3, 4, 5))  # 15

# 키워드 가변 인수 (**kwargs)
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=30, city="Seoul")

# 모든 종류의 매개변수 조합
def complex_function(required, default="기본값", *args, **kwargs):
    print(f"필수: {required}")
    print(f"기본값: {default}")
    print(f"가변 인수: {args}")
    print(f"키워드 가변 인수: {kwargs}")

complex_function("필수값", "변경된값", 1, 2, 3, name="Alice", age=30)

함수의 고급 기능

# 지역 변수와 전역 변수
global_var = "전역 변수"

def test_scope():
    local_var = "지역 변수"
    print(local_var)
    print(global_var)

# global 키워드
count = 0

def increment():
    global count
    count += 1

# 중첩 함수
def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function

add_10 = outer_function(10)
print(add_10(5))  # 15

# 람다 함수 (익명 함수)
square = lambda x: x ** 2
print(square(5))  # 25

# 람다 함수와 내장 함수
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))

모듈과 패키지

모듈 import

# 전체 모듈 import
import math
print(math.pi)
print(math.sqrt(16))

# 특정 함수만 import
from math import pi, sqrt
print(pi)
print(sqrt(16))

# 별칭 사용
import math as m
print(m.pi)

from math import pi as PI
print(PI)

# 모든 것 import (권장하지 않음)
# from math import *

사용자 정의 모듈

# calculator.py 파일 생성
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(a, b):
    if b != 0:
        return a / b
    else:
        return "0으로 나눌 수 없습니다"

# 다른 파일에서 사용
# import calculator
# result = calculator.add(5, 3)

# from calculator import add, subtract
# result = add(5, 3)

패키지

# 패키지 구조 예시
# mypackage/
#     __init__.py
#     module1.py
#     module2.py
#     subpackage/
#         __init__.py
#         submodule.py

# 패키지 import
# from mypackage import module1
# from mypackage.subpackage import submodule

표준 라이브러리 소개

# datetime - 날짜와 시간
from datetime import datetime, date, time
now = datetime.now()
today = date.today()

# os - 운영체제 인터페이스
import os
current_dir = os.getcwd()
os.listdir('.')

# random - 난수 생성
import random
random_number = random.randint(1, 10)
random_choice = random.choice(['사과', '바나나', '체리'])

# json - JSON 데이터 처리
import json
data = {'name': 'Alice', 'age': 30}
json_string = json.dumps(data)
parsed_data = json.loads(json_string)

마무리

이번 1편에서는 Python의 기초 문법과 핵심 개념들을 다뤘습니다:

주요 내용 요약

  • Python 설치 및 환경 설정
  • 기본 문법과 데이터 타입
  • 제어구조 (조건문, 반복문)
  • 함수 정의와 활용
  • 모듈과 패키지 시스템

다음 편 예고

2편 - 중급편에서는 다음 내용을 다룰 예정입니다:

  • 객체지향 프로그래밍 (클래스, 상속)
  • 예외 처리
  • 파일 입출력
  • 정규표현식
  • 데코레이터와 제너레이터

연습 과제

  1. 간단한 계산기 프로그램 만들기
  2. 학생 성적 관리 시스템 만들기
  3. 단어 빈도수 계산 프로그램 만들기

Python의 기초를 탄탄히 다져서 다음 단계로 나아가세요!