🐍 Python 🌱 입문

Python 기초 완전정복

프로그래밍 입문자를 위한 Python 기초

⏱️ 8시간 👁️ 35 조회 ⭐ 추천 강좌
📖 강좌 내용
# Python 기초 완전정복

## 학습 목표
Python 프로그래밍의 기초를 마스터합니다.

## 1. Python이란?
간결하고 읽기 쉬운 범용 프로그래밍 언어입니다.
- 배우기 쉬운 문법
- 풍부한 라이브러리
- 웹, AI, 데이터 분석 등 다양한 활용
- 크로스 플랫폼 지원

## 2. 설치 및 실행

```bash
# 버전 확인
python3 --version

# 파일 실행
python3 app.py

# 대화형 모드
python3
>>> print("Hello")
```

## 3. 변수와 자료형

```python
# 문자열
name = "Kim"
message = "Hello World"

# 숫자
age = 25
price = 19.99
count = 1_000_000 # 가독성을 위한 언더스코어

# 불리언
is_active = True
is_admin = False

# 타입 확인
print(type(name)) # <class "str">
print(type(age)) # <class "int">
```

## 4. 문자열 처리

```python
name = "Python"

# 인덱싱과 슬라이싱
print(name[0]) # P
print(name[-1]) # n
print(name[0:3]) # Pyt
print(name[::-1]) # nohtyP (역순)

# 문자열 메서드
text = " Hello World "
text.strip() # "Hello World"
text.lower() # " hello world "
text.upper() # " HELLO WORLD "
text.replace("World", "Python")
text.split(" ") # 리스트로 분리

# f-string (포맷팅)
name = "Kim"
age = 25
print(f"{name}은 {age}살입니다")
print(f"가격: {price:,.2f}원") # 1,234.56원
```

## 5. 리스트

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

# 접근
print(fruits[0]) # apple
print(fruits[-1]) # cherry
print(fruits[1:3]) # ["banana", "cherry"]

# 수정
fruits[0] = "apricot"
fruits.append("date") # 끝에 추가
fruits.insert(1, "blueberry") # 위치에 삽입
fruits.remove("banana") # 값으로 삭제
del fruits[0] # 인덱스로 삭제
popped = fruits.pop() # 마지막 꺼내기

# 정렬
numbers.sort() # 오름차순
numbers.sort(reverse=True) # 내림차순
sorted_list = sorted(numbers) # 새 리스트 반환

# 리스트 컴프리헨션
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
```

## 6. 딕셔너리

```python
# 생성
person = {
"name": "Kim",
"age": 25,
"city": "Seoul"
}

# 접근
print(person["name"])
print(person.get("email", "없음")) # 기본값 지정

# 수정
person["age"] = 26
person["email"] = "kim@test.com"
del person["city"]

# 메서드
person.keys() # dict_keys(["name", "age", ...])
person.values() # dict_values(["Kim", 26, ...])
person.items() # dict_items([("name", "Kim"), ...])

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

## 7. 조건문

```python
age = 18

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

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

# 논리 연산자
if age >= 18 and is_member:
print("성인 회원")

if age < 13 or age > 65:
print("할인 대상")
```

## 8. 반복문

```python
# for 문
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

# 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 index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")

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

# break, continue
for i in range(10):
if i == 3:
continue # 건너뛰기
if i == 7:
break # 종료
print(i)
```

## 9. 함수

```python
# 기본 함수
def greet(name):
return f"Hello, {name}!"

# 기본값 매개변수
def greet(name, greeting="Hello"):
return f"{greeting}, {name}!"

# 가변 인자
def add(*numbers):
return sum(numbers)

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

# 키워드 인자
def profile(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

profile(name="Kim", age=25, city="Seoul")

# 람다 함수
double = lambda x: x * 2
add = lambda a, b: a + b
```

## 10. 클래스

```python
class User:
def __init__(self, name, age):
self.name = name
self.age = age

def greet(self):
return f"Hello, I am {self.name}"

def birthday(self):
self.age += 1

# 사용
user = User("Kim", 25)
print(user.greet())
user.birthday()
print(user.age) # 26

# 상속
class Admin(User):
def __init__(self, name, age, role):
super().__init__(name, age)
self.role = role

def greet(self):
return f"Hello, I am {self.name} ({self.role})"
```

## 11. 예외 처리

```python
try:
result = 10 / 0
except ZeroDivisionError:
print("0으로 나눌 수 없습니다")
except Exception as e:
print(f"오류 발생: {e}")
else:
print("성공")
finally:
print("항상 실행")

# 예외 발생
def divide(a, b):
if b == 0:
raise ValueError("0으로 나눌 수 없습니다")
return a / b
```

## 12. 파일 처리

```python
# 파일 읽기
with open("file.txt", "r", encoding="utf-8") as f:
content = f.read()
# 또는 줄 단위로
lines = f.readlines()

# 파일 쓰기
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello World")

# JSON 처리
import json

# 읽기
with open("data.json", "r") as f:
data = json.load(f)

# 쓰기
with open("output.json", "w") as f:
json.dump(data, f, indent=2, ensure_ascii=False)
```

## 추천 학습 순서
1. 변수와 자료형
2. 리스트와 딕셔너리
3. 조건문과 반복문
4. 함수 작성
5. 클래스와 객체지향